1 |
|
2 |
|
3 | export 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 |
|
21 | return ret;
|
22 | }
|
23 | }
|
24 |
|
25 |
|
26 |
|
27 | export 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 |
|
45 | return ret;
|
46 | }
|
47 | }
|