Created
August 3, 2021 16:13
-
-
Save amir-arad/ec7c286ff59be2621ecff592f4980409 to your computer and use it in GitHub Desktop.
a typescript map that generates default values if none exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* a map that generates default values if none exists | |
*/ | |
export class MagicMap<K,V> extends Map<K,V> { | |
constructor(private defVal: () => V){ | |
super(); | |
} | |
has = (key:K) => true; | |
get = (key:K): V => { | |
if (!Map.prototype.has.call(this, key)){ | |
this.set(key, this.defVal()); | |
} | |
return Map.prototype.get.call(this, key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment