-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathto-lookup.ts
More file actions
32 lines (28 loc) · 810 Bytes
/
to-lookup.ts
File metadata and controls
32 lines (28 loc) · 810 Bytes
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
export {};
declare global {
interface Array<T> {
/**
* [拡張メソッド]
* 配列をMap<K, V[]>に変換します
* @param keyFn
* @param valueFn
* @return Map
*/
toLookup<K, V>(keyFn: (value: T) => K, valueFn: (value: T) => V): Map<K, V[]>;
}
}
Array.prototype.toLookup = function <T, K, V>(keyFn: (value: T) => K, valueFn: (value: T) => V): Map<K, V[]> {
const items = this as T[];
const convItems = items.map((item) => {
return { key: keyFn(item), value: valueFn(item) };
});
const map = new Map<K, V[]>();
for (const item of convItems) {
if (map.has(item.key)) {
const values = map.get(item.key) as V[];
values.push(item.value);
map.set(item.key, values);
} else map.set(item.key, [item.value]);
}
return map;
};