-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
12 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
) | ||
} |