Skip to content

Commit

Permalink
feat(keyBy): 仅支持函数生成 key
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Mar 1, 2019
1 parent 5141975 commit 8a5a56c
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/keyBy.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import get from './get'
import { ToPathValue } from './toPath'

/**
* 根据 `iteratee` 对 `arr` 进行分组,但只保留最后一个结果。
*
* @param arr 要分组的数据
* @param iteratee 迭代值,字符串或数字表示键路径,函数表示以该函数生成 `key`
* @param iteratee 生成 `key` 的迭代函数
* @returns 分组结果
*/
export default function keyBy<T>(
export default function keyBy<T extends any, K extends keyof any>(
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) => {
res[
iterateeIsFunction
? (iteratee as any)(item, index)
: get(item as any, iteratee as any)
] = item
return res
}, {})
iteratee: (item: T, index: number) => K,
): { [key in K]: T } {
return arr.reduce<{ [key in K]: T }>(
(res, item, index) => {
const key = iteratee(item, index)
res[key] = item
return res
},
{} as any,
)
}

0 comments on commit 8a5a56c

Please sign in to comment.