-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactoryMap.ts
More file actions
34 lines (31 loc) · 1.33 KB
/
FactoryMap.ts
File metadata and controls
34 lines (31 loc) · 1.33 KB
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
export class FactoryMap<K, V> extends Map<K, V> {
private factory?: (k: K) => V;
public constructor(iterableOrDefaultValueFactory?: Iterable<[K, V]> | ((k: K) => V), defaultValueFactory?: (k: K) => V) {
const isFunctionOrUndefined = (f?: Iterable<[K, V]> | ((k: K) => V)): f is (((k: K) => V) | undefined) => iterableOrDefaultValueFactory === undefined || typeof iterableOrDefaultValueFactory === 'function';
if (isFunctionOrUndefined(iterableOrDefaultValueFactory)) {
if (iterableOrDefaultValueFactory && defaultValueFactory) {
throw new Error('Unexpected constructor params');
}
super();
this.factory = iterableOrDefaultValueFactory;
} else {
super(iterableOrDefaultValueFactory);
this.factory = defaultValueFactory;
}
}
public get(key: K, defaultValueFactory?: (k: K) => V): V;
public get(key: K, defaultValueFactory?: (k: K) => V | undefined): V | undefined {
let r = super.get(key);
if (r === undefined) {
if (defaultValueFactory) {
r = defaultValueFactory(key);
} else if (this.factory) {
r = this.factory(key);
}
if (r !== undefined) {
super.set(key, r);
}
}
return r;
}
}