diff --git a/src/number/sum.ts b/src/number/sum.ts index 556f90f2..7dc539d1 100644 --- a/src/number/sum.ts +++ b/src/number/sum.ts @@ -1,6 +1,8 @@ /** - * Sum all numbers in an array. Optionally provide a function to - * convert objects in the array to number values. + * Add up numbers related to an array in 1 of 2 ways: + * 1. Sum all numbers in an array of numbers + * 2. Sum all numbers returned by a callback function that maps + * each item in an array to a number. * * @see https://radashi-org.github.io/reference/array/sum * @example @@ -14,14 +16,14 @@ * {value: 3} * ], (item) => item.value) * // => 6 + * + * sum([true, false, true], (item) => item ? 1 : 0) + * // => 2 * ``` */ -export function sum(array: readonly T[]): number -export function sum( - array: readonly T[], - fn: (item: T) => number, -): number -export function sum( +export function sum(array: readonly number[]): number +export function sum(array: readonly T[], fn: (item: T) => number): number +export function sum( array: readonly any[], fn?: (item: T) => number, ): number { diff --git a/tests/number/sum.test.ts b/tests/number/sum.test.ts index 73d9b892..12dbfaa4 100644 --- a/tests/number/sum.test.ts +++ b/tests/number/sum.test.ts @@ -17,4 +17,19 @@ describe('sum', () => { const result = _.sum(cast(null)) expect(result).toBe(0) }) + test('gracefully handles boolean input list', () => { + const list = [true, false, true, false, true] + const result = _.sum(list, x => (x ? 1 : 0)) + expect(result).toBe(3) + }) + + test('gracefully handles matrix input', () => { + const list = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ] + const result = _.sum(list, x => _.sum(x)) + expect(result).toBe(45) + }) })