Skip to content

Instantly share code, notes, and snippets.

@amir-arad
Created August 3, 2021 16:13
Show Gist options
  • Save amir-arad/ec7c286ff59be2621ecff592f4980409 to your computer and use it in GitHub Desktop.
Save amir-arad/ec7c286ff59be2621ecff592f4980409 to your computer and use it in GitHub Desktop.
a typescript map that generates default values if none exists
/**
* 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