UNPKG

advanced-map-initialized

Version:
58 lines 1.7 kB
"use strict"; const tslib_1 = require("tslib"); const advanced_map_base_1 = tslib_1.__importDefault(require("advanced-map-base")); /** * Objects of this class call their `init` function * every time`get()`is invoked upon non-existing key. * As a result, `get()` never return `undefined`. */ class Initialized extends advanced_map_base_1.default { /** * @param Map A constructor (a.k.a class) that creates a Map-like object. * @param init Function that takes a yet-to-initialized key and returns default value. */ constructor(Map, init) { super(Map); this.init = init; } /** * Check if a certain key is initialized/set. * @returns `true` if given key is initialized or set, `false` otherwise. */ has(key) { return this.data.has(key); } /** * If `key` exists, return corresponding value. * Otherwise, call `init` function and add its returning value to the map. * @param key Map's key. * @returns Corresponding value. */ get(key) { const { data } = this; if (data.has(key)) return data.get(key); const value = this.init(key); data.set(key, value); return value; } /** * Set `key` to point to `value`. * @param key Key. * @param value Value. */ set(key, value) { this.data.set(key, value); return this; } /** * Delete a key if it exists. * @param key Key to be deleted. * @returns `true` if deleted key existed and `false` otherwise. */ delete(key) { return this.data.delete(key); } } module.exports = Initialized; //# sourceMappingURL=index.js.map