Created
June 27, 2024 11:44
-
-
Save janhesters/8cd77d4b17cdcbf843a0f9dff8272bd0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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