-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.ts
37 lines (27 loc) · 1.03 KB
/
index.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
type Resolver<T> = (item: T) => any;
type Indexer<T> = number | keyof T | symbol;
type ValueResolver<T> = Indexer<T> | Resolver<T>;
export {};
declare global {
interface Array<T> {
uniqueBy(valueResolver?: ValueResolver<T>): T[];
}
}
if (typeof Array.prototype.uniqueBy !== 'function')
Object.defineProperty(Array.prototype, 'uniqueBy', {
writable: true,
configurable: true,
value: function <T>(this: T[], valueResolver?: ValueResolver<T>) {
if (!(valueResolver != null)) return [...new Set(this)];
const key = typeof valueResolver !== 'function' && valueResolver,
map = new Map<any, T>();
valueResolver = key
? (item: Record<Indexer<T>, any>) => item?.[key] ?? item
: valueResolver;
for (const item of this) {
const key = (valueResolver as Resolver<T>)(item);
if (!map.has(key)) map.set(key, item);
}
return [...map.values()];
}
});