Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sum): improve type for list of booleans #143

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})
})