Skip to content

Commit

Permalink
feat: add groupBy
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Feb 12, 2019
1 parent 012f723 commit 0aee8ac
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
26 changes: 26 additions & 0 deletions src/groupBy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import get from './get'
import { ToPathValue } from './toPath'

/**
* 根据 `iteratee` 对 `arr` 进行分组。
*
* @param arr 要分组的数据
* @param iteratee 迭代值,字符串或数字表示键路径,函数表示以该函数生成 `key`
* @returns 分组结果
*/
export default function groupBy<T>(
arr: T[],
iteratee: ToPathValue | ((item: T, index: number) => any)
): { [key: string]: T[] } {
const iterateeIsFunction = typeof iteratee === 'function'
return arr.reduce<{ [key: string]: T[] }>((res, item, index) => {
const key = iterateeIsFunction
? (iteratee as any)(item, index)
: get(item as any, iteratee as any)
if (!res[key]) {
res[key] = []
}
res[key].push(item)
return res
}, {})
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export { default as formatDate } from './formatDate'
export { default as formatDateDiff } from './formatDateDiff'
export { default as get } from './get'
export { default as getType } from './getType'
export { default as groupBy } from './groupBy'
export { default as has } from './has'
export { default as inBrowser } from './inBrowser'
export { default as inNode } from './inNode'
Expand Down
4 changes: 2 additions & 2 deletions src/keyBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ export default function keyBy<T>(
iteratee: ToPathValue | ((item: T, index: number) => any)
): { [key: string]: T } {
const iterateeIsFunction = typeof iteratee === 'function'
return arr.reduce((res, item, index) => {
return arr.reduce<{ [key: string]: T }>((res, item, index) => {
res[
iterateeIsFunction
? (iteratee as any)(item, index)
: get(item as any, iteratee as any)
] = item
return res
}, {} as any)
}, {})
}
8 changes: 8 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1591,3 +1591,11 @@ describe('chunk', () => {
expect(vtils.chunk([1, 2, 3], 2, 4)).toEqual([[1, 2], [3, 4]])
})
})

describe('groupBy', () => {
test('ok', () => {
expect(vtils.groupBy([6.1, 4.2, 6.3], Math.floor)).toEqual({ 4: [4.2], 6: [6.1, 6.3] })
expect(vtils.groupBy(['one', 'two', 'three'], 'length')).toEqual({ 3: ['one', 'two'], 5: ['three'] })
expect(vtils.groupBy([{ i: 1 }, { i: 2 }, { i: 2, x: 0 }], 'i')).toEqual({ 1: [{ i: 1 }], 2: [{ i: 2 }, { i: 2, x: 0 }] })
})
})

0 comments on commit 0aee8ac

Please sign in to comment.