Skip to content

Instantly share code, notes, and snippets.

@bitsapien
Last active April 5, 2021 13:55
Show Gist options
  • Save bitsapien/4fb63422d1646250bef81a18287af80e to your computer and use it in GitHub Desktop.
Save bitsapien/4fb63422d1646250bef81a18287af80e to your computer and use it in GitHub Desktop.
Caching is fun ! A higher order function to add caching on your pure function.
/**
* @typedef {Object} CacheResponse
* @property {any} data - The value that you a general call would return.
* @property {Object} cache - The cache store merged with the current function call.
*/
/**
* Caching function or memoizer that uses a custom hashing key algo.
* @param {function} fn - Pure function whose value you want to cache.
* @param {Array} args - The list of arguments you want to call 'fn' with.
* @param {Object} cache - Bunch of key value pairs that is literally your cache store.
* @param {function} hashingFunction - The hashing algo appropriate for your case.
* @return {CacheResponse}
*/
const withCache = function (fn, args, cache, hashingFunction) {
const cacheKey = hashingFunction(args);
if(!cache[cacheKey]) {
cache[cacheKey] = fn(...args);
}
return {data: cache[cacheKey], cache: cache};
}
/* Usage */
const add = (x,y) => x + y;
const hashFunction = args => JSON.stringify(args);
let cache = {}
const response = withCache(add, [1,2], cache, hashFunction);
cache = response["cache"];
const data = response["data"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment