@parzh/cache
Version:
Cache manager for dynamic object properties
62 lines (61 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class Cache extends WeakMap {
/**
* Peel off all key ownership constraints.
* __Use for edge cases and/or as the last resort.__
* @example
* cache.untyped.setValue(thing, "customKey", 42);
*/
get untyped() {
return this;
}
/**
* Invalidate cached value
* @param obj Cacheable object
* @param key Key of cacheable object
*/
invalidate(obj, keys) {
const _keys = [].concat(keys);
for (const key of _keys)
this._invalidate(obj, key);
}
/**
* Store value in cache
* @param obj Cacheable object
* @param key Key of the cacheable object
* @param value Value to be stored in cache
*/
setValue(obj, key, value) {
this._setEntry(obj, key, { value, valid: true });
}
getValue(obj, key, init) {
const entry = this._getEntry(obj, key);
if (entry && entry.valid)
return entry.value;
if (init == null)
return;
const value = init();
this.setValue(obj, key, value);
return value;
}
/** @override */
get(obj) {
return super.get(obj) || {};
}
// ***
_getEntry(obj, key) {
return this.get(obj)[key];
}
_setEntry(obj, key, entry) {
this.set(obj, Object.assign(this.get(obj), { [key]: entry }));
}
_invalidate(obj, key) {
const entry = this._getEntry(obj, key);
if (entry) {
entry.valid = false;
entry.value = void 0;
}
}
}
exports.Cache = Cache;