From 16ee0634b41aa8c967f46b0d094578d8408c11dc Mon Sep 17 00:00:00 2001 From: minsoo kim Date: Wed, 2 Aug 2023 11:52:14 +0900 Subject: [PATCH] =?UTF-8?q?practice:=201=EC=A3=BC=EC=B0=A8=202=EB=B2=88=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=A0=9C=EC=B6=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1week/02/__submit__/minsoo-web.test.ts | 19 ++++++++++++++++- .../src/1week/02/__submit__/minsoo-web.ts | 21 ++++++++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/example/src/1week/02/__submit__/minsoo-web.test.ts b/packages/example/src/1week/02/__submit__/minsoo-web.test.ts index b62bdfd..7f30ec6 100644 --- a/packages/example/src/1week/02/__submit__/minsoo-web.test.ts +++ b/packages/example/src/1week/02/__submit__/minsoo-web.test.ts @@ -2,6 +2,23 @@ import { accumulate } from './minsoo-web' describe('accumulate', () => { it('case: 1', () => { - expect(accumulate([1, 2, 3, 4, 5])).toBe(15) + const foo = [1, 2, 3, 4, 5] + + expect(accumulate(foo)).toBe(15) + expect(accumulate(foo)).toBe(15) + }) + + it('case: 2', () => { + const foo = [1, 2, 3, 4, 5] + + expect(accumulate(foo, 10)).toBe(25) + expect(accumulate(foo, 10)).toBe(25) + }) + + it('case: 3', () => { + const foo = [-1, 2, -3, 4, 5] + + expect(accumulate(foo)).toBe(7) + expect(accumulate(foo)).toBe(7) }) }) diff --git a/packages/example/src/1week/02/__submit__/minsoo-web.ts b/packages/example/src/1week/02/__submit__/minsoo-web.ts index 1f9be29..9908a00 100644 --- a/packages/example/src/1week/02/__submit__/minsoo-web.ts +++ b/packages/example/src/1week/02/__submit__/minsoo-web.ts @@ -1,9 +1,16 @@ -export function accumulate(arr: number[]): number { - let accumulator = 0 +const sum = (a: number, b: number): number => a + b - for (let i = 0; i < arr.length; i += 1) { - accumulator += arr[i] - } - - return accumulator +/** + * + * 접근 방법: + * 지난 2주차 때 얘기 나눴던 내용과 비슷한 맥락으로 리펙토링 해봤습니다. + * reduce 라는 내장 메소드가 이미 있음에도, sum 이라는 함수를 따로 선언함으로써 reduce를 직관적으로 사용할 수 있고 + * accumulate 함수를 사용하는 사람 입장에서, 구현체를 추상화함으로써 합계만을 기대할 수 있게 추상화했습니다. + * + * @param arr 합을 계산할 배열입니다. + * @param initialValue 초기 값을 지정할 수 있습니다. 기본 값은 0입니다. + * @returns 배열내의 모든 요소를 더한 값을 return 합니다. + */ +export function accumulate(arr: number[], initialValue = 0): number { + return arr.reduce(sum, initialValue) }