-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathgroupBy.ts
49 lines (41 loc) · 1.69 KB
/
groupBy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {isArrayLike} from './internal/array'
import {baseIteratee} from './internal/baseIteratee'
import isPlainObject from './isPlainObject'
import type {ValueIteratee} from './internal/baseIteratee.type'
type PropertyName = string | number | symbol
export function groupBy<T>(collection: T[] | null | undefined, iteratee?: ValueIteratee<T>): Record<string, T[]>
export function groupBy<T extends object>(
collection: T | null | undefined,
iteratee?: ValueIteratee<T[keyof T]>,
): Record<string, T[keyof T][]>
export function groupBy(collection: unknown, iteratee?: ValueIteratee<unknown>): Record<string, unknown[]> {
if (collection == null) {
return {}
}
const iterFn = baseIteratee(iteratee ?? ((v: unknown) => v))
const result: Record<string, unknown[]> = {}
if (isArrayLike(collection)) {
const arr = collection as ArrayLike<unknown>
for (let i = 0; i < arr.length; i++) {
const value = arr[i]
const key = iterFn(value, i, arr)
const stringKey = key == null ? 'undefined' : String(key)
const group = result[stringKey] || (result[stringKey] = [])
group.push(value)
}
return result
}
if (isPlainObject(collection)) {
const values = Object.values(collection as Record<PropertyName, unknown>)
for (let i = 0; i < values.length; i++) {
const value = values[i]
const key = iterFn(value, i, values)
const stringKey = key == null ? 'undefined' : String(key)
const group = result[stringKey] || (result[stringKey] = [])
group.push(value)
}
return result
}
return {}
}
export default groupBy