-
Notifications
You must be signed in to change notification settings - Fork 0
/
map-object.utility.ts
60 lines (54 loc) · 1.85 KB
/
map-object.utility.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
/**
* static members for @type {Map<K, V>}
*
* @export
*/
export class MapObjectUtility {
/**
* gets @type {Map<string, TValue>} from an object
*/
static getMap<TValue>(
o: { [index: string]: any },
valueGetter?: (propertyName: string, propertyValue: TValue) => TValue
): Map<string, TValue> | null {
if (!o) {
console.warn('object to be mapped is not truthy');
return null;
}
const iterable = Object.keys(o).map(propertyName => {
const propertyValue = o[propertyName] as TValue;
const value = valueGetter ? valueGetter(propertyName, propertyValue) : propertyValue;
return [propertyName, value] as [string, TValue];
});
return new Map<string, TValue>(iterable);
}
/**
* gets @type {Map<string, TValue>} from an object
* of @type {Array<{ key: string; value: any }>}
*
* @see https://stackoverflow.com/a/26265095/22944
*/
static getMapFromKeyValuePairs<TValue>(
pairs: Array<{ key: string; value: any }>,
valueGetter?: (propertyName: string, propertyValue: TValue) => TValue
): Map<string, TValue> | null {
const initialValue: { [index: string]: TValue } = {};
const o = pairs.reduce((a, i) => {
a[i.key] = i.value;
return a;
}, initialValue);
return MapObjectUtility.getMap(o, valueGetter);
}
/**
* gets an object with string property names
* from a map with @types {string | number}
*
* @see https://macwright.org/2017/03/13/maps-not-strictly-better.html
*/
static getObject(map: Map<string | number, any>): { [key: string]: any } {
const o: { [key: string]: any } = {};
if (!map) { return o; }
map.forEach((v: any, k: string | number) => o[k] = v);
return o;
}
}