Skip to content

Commit

Permalink
fix(types): remove type constraint for mapped array passed to sum (#…
Browse files Browse the repository at this point in the history
…143)

Co-authored-by: Alec Larson <[email protected]>
  • Loading branch information
MarlonPassos-git and aleclarson committed Aug 6, 2024
1 parent 24307ef commit dea0f50
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/number/sum.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -14,14 +16,14 @@
* {value: 3}
* ], (item) => item.value)
* // => 6
*
* sum([true, false, true], (item) => item ? 1 : 0)
* // => 2
* ```
*/
export function sum<T extends number>(array: readonly T[]): number
export function sum<T extends object>(
array: readonly T[],
fn: (item: T) => number,
): number
export function sum<T extends object | number>(
export function sum(array: readonly number[]): number
export function sum<T>(array: readonly T[], fn: (item: T) => number): number
export function sum<T>(
array: readonly any[],
fn?: (item: T) => number,
): number {
Expand Down
15 changes: 15 additions & 0 deletions tests/number/sum.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})

0 comments on commit dea0f50

Please sign in to comment.