Last active
September 16, 2024 19:26
-
-
Save Fasteroid/5a0379e1c16b8a0765bbac59534f83a8 to your computer and use it in GitHub Desktop.
Variations of javascript's "Map"
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
/** | |
* Like a normal {@link Map}, but if you get a key that doesn't exist, it will automatically make it exist. | |
*/ | |
export class AutoMap<K, V> extends Map<K, V> { | |
/** | |
* @param computer Instantiates default value for keys that don't exist | |
*/ | |
public constructor( private computer: (key: K) => V ){ super(); } | |
public override get(key: K): V { | |
let value = super.get(key); | |
if( value === undefined ){ | |
value = this.computer(key); | |
super.set(key, value); | |
} | |
return value; | |
} | |
} | |
/** | |
* Like a normal {@link WeakMap}, but if you get a key that doesn't exist, it will automatically make it exist. | |
*/ | |
export class WeakAutoMap<K extends object, V> extends WeakMap<K, V> { | |
/** | |
* @param computer Instantiates default value for keys that don't exist | |
*/ | |
public constructor( private computer: (key: K) => V ){ super(); } | |
public override get(key: K): V { | |
let value = super.get(key); | |
if( value === undefined ){ | |
value = this.computer(key); | |
super.set(key, value); | |
} | |
return value; | |
} | |
} | |
function isPrimitive(val: unknown): boolean { | |
return val !== null && typeof val !== "object" && typeof val !== "function" | |
} | |
/** | |
* Like a normal {@link WeakMap}, but you can store primitives on it. | |
*/ | |
export class SemiWeakMap<K, V> extends WeakMap<any, V> { | |
private primitives = new Map<K, V>(); | |
public override get(key: K): V | undefined { | |
return isPrimitive(key) ? this.primitives.get(key) : super.get(key); | |
} | |
public override set(key: K, value: V): this { | |
isPrimitive(key) ? this.primitives.set(key, value) : super.set(key, value); | |
return this; | |
} | |
public override has(key: K): boolean { | |
return isPrimitive(key) ? this.primitives.has(key) : super.has(key); | |
} | |
public override delete(key: K): boolean { | |
return isPrimitive(key) ? this.primitives.delete(key) : super.delete(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment