Skip to content

Instantly share code, notes, and snippets.

@kendallroth
Created August 25, 2022 05:10
Show Gist options
  • Save kendallroth/2914a5a5d62bccbf1634329405fcac7f to your computer and use it in GitHub Desktop.
Save kendallroth/2914a5a5d62bccbf1634329405fcac7f to your computer and use it in GitHub Desktop.
Simple TS caching mechanism (use Map instead though...)
type CacheKey = string | number;
interface Cache<T> {
/** Number of cache entries */
readonly count: number;
/** Get an item from the cache */
get: (key: CacheKey) => T | null;
/** Check whether cache contains a given item */
has: (key: CacheKey) => boolean;
/** Cached items */
cache: Record<CacheKey, T>;
/** Remove an item from the cache */
remove: (key: CacheKey) => void;
/** Add/set an item in the cache */
set: (key: CacheKey, item: T) => void;
}
/**
* Create a cache map structure
*
* Use to reduce API calls for potentially duplicate data requests.
*/
export const createCache = <T>(): Cache<T> => {
const cache: Record<CacheKey, T> = {};
const get = (key: CacheKey): T | null => {
return cache[key] ?? null;
};
const has = (key: CacheKey) => Boolean(get(key));
const remove = (key: CacheKey) => {
delete cache[key];
};
const set = (key: CacheKey, item: T) => {
cache[key] = item;
};
return {
get count() {
return Object.keys(cache).length;
},
cache,
get,
has,
remove,
set,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment