-
Notifications
You must be signed in to change notification settings - Fork 2
/
toMap.ts
71 lines (64 loc) · 1.81 KB
/
toMap.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* eslint-disable @typescript-eslint/ban-types */
// Return all keys of an object that have value types we can use as a map key
type MappableKeys<T> = NonNullable<
{
[K in keyof T]: T[K] extends string | number | undefined ? K : never
}[keyof T]
>
/**
* ### toMap(array, key, target?)
*
* Create a lookup map out of an `array` of objects, with a lookup `key` and an optional `target`.
*
* ```js
* flocky.toMap(
* [
* { id: 1, name: 'Stanley', age: 64 },
* { id: 2, name: 'Juliet', age: 57 },
* { id: 3, name: 'Alex', age: 19 }
* ],
* 'id'
* )
* // -> {
* // -> 1: { id: 1, name: 'Stanley', age: 64 },
* // -> 2: { id: 2, name: 'Juliet', age: 57 },
* // -> 3: { id: 3, name: 'Alex', age: 19 }
* // -> }
*
* flocky.toMap(
* [
* { id: 1, name: 'Stanley', age: 64 },
* { id: 2, name: 'Juliet', age: 57 },
* { id: 3, name: 'Alex', age: 19 }
* ],
* 'name',
* 'age'
* )
* // -> { Stanley: 64, Juliet: 57, Alex: 19 }
* ```
*/
export function toMap<Element extends object, Key extends MappableKeys<Element>>(
array: Array<Element>,
key: Key
): { [key: string]: Element | undefined }
export function toMap<
Element extends object,
Key extends MappableKeys<Element>,
Target extends keyof Element,
>(array: Array<Element>, key: Key, target: Target): { [key: string]: Element[Target] | undefined }
export function toMap<
Element extends object,
Key extends MappableKeys<Element>,
Target extends keyof Element,
>(
array: Array<Element>,
key: Key,
target?: Target
): { [key: string]: Element | Element[Target] | undefined } {
const map: { [key: string]: Element | Element[Target] | undefined } = {}
array.map((element) => {
if (!element[key]) return
map[element[key] as unknown as string] = target ? element[target] : element
})
return map
}