Skip to content

Instantly share code, notes, and snippets.

@myrdd
Created December 21, 2017 17:09
Show Gist options
  • Save myrdd/958fe8548b73fa9cc715dc701b2ca11c to your computer and use it in GitHub Desktop.
Save myrdd/958fe8548b73fa9cc715dc701b2ca11c to your computer and use it in GitHub Desktop.
MapBuilder
interface IMapValueFactory<K, T> {
construct: (key: K) => T;
}
interface IMapBuilder<K, T> {
maybeConstruct: (key: K) => void;
get: (
((key: K, maybeConstruct?: boolean) => T | undefined) &
((key: K, maybeConstruct: true) => T)
);
}
class MapBuilder<K, T> extends Map<K, T> implements IMapBuilder<K, T> {
private valueFactory: IMapValueFactory<K, T>;
constructor(valueFactory: IMapValueFactory<K, T>) {
super();
this.valueFactory = valueFactory;
}
public maybeConstruct(key: K) {
if (!this.has(key)) {
this.set(key, this.valueFactory.construct(key));
}
}
public get(key: K, maybeConstruct: boolean = false) {
if (maybeConstruct) this.maybeConstruct(key);
return super.get(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment