56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
// TODO: We may want to move this to @xocash/primitives.
|
|
|
|
export class Memoizer {
|
|
private cache = new Map<string, any>();
|
|
|
|
/**
|
|
* Gets a cached value for the given key, computing it if it doesn't exist.
|
|
*
|
|
* @param key - The key to look up or store the value under
|
|
* @param compute - Function to compute the value if it's not cached
|
|
* @returns The cached or computed value
|
|
*/
|
|
get<K extends string, V>(key: K, compute: () => V): V {
|
|
if (!this.cache.has(key)) {
|
|
this.cache.set(key, compute());
|
|
}
|
|
return this.cache.get(key) as V;
|
|
}
|
|
|
|
/**
|
|
* Checks if a value exists for the given key.
|
|
*
|
|
* @param key - The key to check
|
|
* @returns Whether the key exists in the cache
|
|
*/
|
|
has(key: string): boolean {
|
|
return this.cache.has(key);
|
|
}
|
|
|
|
/**
|
|
* Deletes a cached value.
|
|
*
|
|
* @param key - The key to delete
|
|
* @returns Whether a value was deleted
|
|
*/
|
|
delete(key: string): boolean {
|
|
return this.cache.delete(key);
|
|
}
|
|
|
|
/**
|
|
* Clears all cached values.
|
|
*/
|
|
clear(): void {
|
|
this.cache.clear();
|
|
}
|
|
|
|
/**
|
|
* Gets all cached keys.
|
|
*
|
|
* @returns Array of cached keys
|
|
*/
|
|
keys(): string[] {
|
|
return Array.from(this.cache.keys());
|
|
}
|
|
}
|