@parzh/cache
Version:
Cache manager for dynamic object properties
58 lines (57 loc) • 2.04 kB
TypeScript
/** @private */
interface Entry<Value> {
valid: boolean;
value: Value | void;
}
/** @private */
declare type Entries<Cacheable extends object> = {
[Key in keyof Cacheable]?: Entry<Cacheable[Key]>;
};
export declare class Cache<Cacheable extends object, __Key extends keyof Cacheable = keyof Cacheable> extends WeakMap<Cacheable, Entries<Cacheable>> {
/**
* Peel off all key ownership constraints.
* __Use for edge cases and/or as the last resort.__
* @example
* cache.untyped.setValue(thing, "customKey", 42);
*/
readonly untyped: Cache<Record<keyof any, any>>;
/**
* Invalidate cached value
* @param obj Cacheable object
* @param key Key of cacheable object
*/
invalidate(obj: Cacheable, key: __Key): void;
/**
* Invalidate several cached values simultaneously
* @param obj Cacheable object
* @param keys Array of keys of cacheable object
*/
invalidate(obj: Cacheable, keys: __Key[]): void;
/**
* Store value in cache
* @param obj Cacheable object
* @param key Key of the cacheable object
* @param value Value to be stored in cache
*/
setValue<Key extends __Key>(obj: Cacheable, key: Key, value: Cacheable[Key]): void;
/**
* Get value from cache
* @param obj Cacheable object
* @param key Key of cacheable object
*/
getValue(obj: Cacheable, key: __Key): Cacheable[__Key] | void;
/**
* Get value from cache.
* If cache is invalid, it will be initialized (see description for `init` parameter).
* @param obj Cacheable object
* @param key Key of cacheable object
* @param init Initializer for non-existent, undefined or invalid values
*/
getValue<Key extends __Key>(obj: Cacheable, key: Key, init: () => Cacheable[Key]): Cacheable[Key];
/** @override */
get(obj: Cacheable): Entries<Cacheable>;
private _getEntry;
private _setEntry;
private _invalidate;
}
export {};