| 52 | } |
| 53 | |
| 54 | getOrAdd(key: TKey, initializer: TValue | Promise<TValue> | Promise<undefined> | (() => Promise<TValue | undefined> | TValue | undefined)): Promise<TValue | undefined> | TValue | undefined { |
| 55 | let result: Promise<TValue | undefined> | TValue | undefined = this.map.get(key); |
| 56 | |
| 57 | // if we don't get a match, then we'll try to set the value with the initializer |
| 58 | if (is.nullish(result)) { |
| 59 | // if the initializer is a function, then we'll call it to get the value |
| 60 | if (is.function(initializer)) { |
| 61 | result = initializer(); |
| 62 | } |
| 63 | |
| 64 | // if we're not handed a promise or a value, then we're done |
| 65 | if (is.nullish(result)) { |
| 66 | return undefined; |
| 67 | } |
| 68 | |
| 69 | // set the value in the map to the result of the initializer |
| 70 | this.map.set(key, result); |
| 71 | |
| 72 | // if the initializer is a promise, then we'll tack on a bit of logic to remove the value from the map if the promise resolves to undefined |
| 73 | if (is.promise(result)) { |
| 74 | return result.then(v => { |
| 75 | if (is.nullish(v)) { |
| 76 | this.map.delete(key); |
| 77 | } |
| 78 | return v; |
| 79 | }); |
| 80 | } |
| 81 | } |
| 82 | return result; |
| 83 | } |
| 84 | set(key: TKey, value: Promise<TValue> | TValue): this { |
| 85 | this.map.set(key, value); |
| 86 | return this; |