Skip to content

Commit

Permalink
feat: add sumBy
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 21, 2019
1 parent c7fc3e5 commit 1154786
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export { default as startsWith } from './startsWith'
export { default as stopEventPropagation } from './stopEventPropagation'
export { default as storage } from './storage'
export { default as sum } from './sum'
export { default as sumBy } from './sumBy'
export { default as supportPassiveEventListener } from './supportPassiveEventListener'
export { default as times } from './times'
export { default as toDate } from './toDate'
Expand Down
13 changes: 13 additions & 0 deletions src/sumBy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* 根据 `iteratee` 返回的结果计算传入值的总和。
*
* @param array 传入的数组
* @param iteratee 迭代函数
* @returns 总和
*/
export default function sumBy<T>(array: T[], iteratee: (item: T) => number): number {
return array.reduce<number>((total, item) => {
total += iteratee(item)
return total
}, 0)
}
8 changes: 8 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1519,3 +1519,11 @@ describe('sum', () => {
expect(vtils.sum([4, 2], 8, [6], [])).toBe(20)
})
})

describe('sumBy', () => {
test('ok', () => {
expect(vtils.sumBy([4, 2, 8, 6], item => item)).toBe(20)
expect(vtils.sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], item => item.n)).toBe(20)
expect(vtils.sumBy([vtils.range(0, 10), vtils.range(0, 5)], item => item.length)).toBe(15)
})
})

0 comments on commit 1154786

Please sign in to comment.