Skip to content

Instantly share code, notes, and snippets.

@janhesters
Created June 27, 2024 11:44
Show Gist options
  • Save janhesters/8cd77d4b17cdcbf843a0f9dff8272bd0 to your computer and use it in GitHub Desktop.
Save janhesters/8cd77d4b17cdcbf843a0f9dff8272bd0 to your computer and use it in GitHub Desktop.
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = args.toString();
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
function add(a, b) {
return a + b;
}
const memoizedAdd = memoize(add);
console.log(memoizedAdd(2, 3)); // Calculates and caches result
console.log(memoizedAdd(2, 3)); // Returns cached result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment