UNPKG

1.02 kBJavaScriptView Raw
1// @flow strict-local
2
3export class DefaultMap<K, V> extends Map<K, V> {
4 _getDefault: K => V;
5
6 constructor(getDefault: K => V, entries?: Iterable<[K, V]>) {
7 super(entries);
8 this._getDefault = getDefault;
9 }
10
11 get(key: K): V {
12 let ret;
13 if (this.has(key)) {
14 ret = super.get(key);
15 } else {
16 ret = this._getDefault(key);
17 this.set(key, ret);
18 }
19
20 // $FlowFixMe
21 return ret;
22 }
23}
24
25// Duplicated from DefaultMap implementation for Flow
26// Roughly mirrors https://github.com/facebook/flow/blob/2eb5a78d92c167117ba9caae070afd2b9f598599/lib/core.js#L617
27export class DefaultWeakMap<K: {...}, V> extends WeakMap<K, V> {
28 _getDefault: K => V;
29
30 constructor(getDefault: K => V, entries?: Iterable<[K, V]>) {
31 super(entries);
32 this._getDefault = getDefault;
33 }
34
35 get(key: K): V {
36 let ret;
37 if (this.has(key)) {
38 ret = super.get(key);
39 } else {
40 ret = this._getDefault(key);
41 this.set(key, ret);
42 }
43
44 // $FlowFixMe
45 return ret;
46 }
47}