Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created September 11, 2021 04:52
Show Gist options
  • Save tjinlag/d03e79884cd36c6d83d98e5eb93025b0 to your computer and use it in GitHub Desktop.
Save tjinlag/d03e79884cd36c6d83d98e5eb93025b0 to your computer and use it in GitHub Desktop.
memoize a function with an optional resolver to compute the proper key
const memoize = function(func, resolver) {
const cache = new Map();
return (...args) => {
const key = resolver ? resolver.apply(this, args) : args[0];
if (cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment