@botonic/plugin-contentful
Version:
## What Does This Plugin Do?
50 lines • 1.24 kB
JavaScript
export class Singleton {
constructor(factory) {
this.factory = factory;
this.isValueSet = false;
}
get value() {
if (!this.isValueSet) {
this.factoryOutput = this.factory();
this.isValueSet = true;
}
return this.factoryOutput;
}
}
/**
* Singletons dictionary accessible through a string
*/
export class SingletonMap {
constructor(map) {
this.map = {};
for (const [k, v] of Object.entries(map)) {
this.map[k] = new Singleton(v);
}
}
value(key) {
const lazy = this.map[key];
if (!lazy) {
throw new Error(`No factory for key ${key}`);
}
return lazy.value;
}
}
/**
* Given a factory function (string) => T,
* it ensures that we don't invoke it more than once per each input value
*/
export class DynamicSingletonMap {
constructor(factories) {
this.factories = factories;
this.values = {};
}
value(key) {
if (!(key in this.values)) {
const val = this.factories(key);
this.values[key] = val;
return val;
}
return this.values[key];
}
}
//# sourceMappingURL=singletons.js.map