/
index.ts
42 lines (39 loc) · 861 Bytes
/
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
38
39
40
41
42
export type Dict<T> = {
[anythingWeWant: string]: T | undefined;
};
// Array.prototype.map, but for Dict
export function mapDict<T, S>(
dict: Dict<T>,
fn: (arg: T, idx: number) => S
): Dict<S> {
const out: Dict<S> = {};
Object.keys(dict).forEach((dKey, idx) => {
const thisItem = dict[dKey];
if (typeof thisItem !== "undefined") {
out[dKey] = fn(thisItem, idx);
}
});
return out;
}
mapDict(
{
a: "a",
b: "b"
},
str => ({ val: str })
);
// Array.prototype.reduce, but for Dict
export function reduceDict<T, S>(
dict: Dict<T>,
reducer: (val: S, item: T, idx: number) => S,
initialVal: S
) {
let val: S = initialVal;
Object.keys(dict).forEach((dKey, idx) => {
const thisItem = dict[dKey];
if (typeof thisItem !== "undefined") {
val = reducer(val, thisItem, idx);
}
});
return val;
}