Skip to content

Instantly share code, notes, and snippets.

@shawn-dsz
Created December 19, 2021 10:13
Show Gist options
  • Save shawn-dsz/a26d187ab8ba9162706a89a48a4444b4 to your computer and use it in GitHub Desktop.
Save shawn-dsz/a26d187ab8ba9162706a89a48a4444b4 to your computer and use it in GitHub Desktop.
create memoize function
const createHash = (item) => JSON.stringify(item);
const memoize = (original) => {
const cache = {};
return (...args) => {
const hash = createHash(args);
if (cache.hasOwnProperty(hash)) {
return cache[hash];
}
cache[hash] = original(...args);
return cache[hash];
};
};
const foo = (a, b, c) => {
console.log(`I do some expensive computation with ${a}, ${b}, ${c}`);
return a + b + c;
};
const memoizedFoo = memoize(foo);
console.log(memoizedFoo(1, 2, 3));
console.log(memoizedFoo(2, 5, 6));
console.log(memoizedFoo(1, 2, 3));
console.log(memoizedFoo(2, 5, 6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment