Created
August 24, 2023 06:49
-
-
Save helloris25/aa868ab5cf2951d8d8a69d602da7f3d6 to your computer and use it in GitHub Desktop.
simple memoize
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 memo(fn) { | |
const cache = new Map(); | |
return function () { | |
if (!cache.has(fn)) { | |
cache.set(fn, new Map()); | |
} | |
const argsKey = JSON.stringify(arguments); | |
if (!cache.get(fn)?.get(argsKey)) { | |
cache.get(fn).set(argsKey, fn(...arguments)); | |
} | |
return cache.get(fn)?.get(argsKey); | |
}; | |
} | |
const memoized = memo((x, y) => x + y); | |
console.log(memoized(2, 2)); | |
console.log(memoized(2, 2)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment