Skip to content

Instantly share code, notes, and snippets.

@helloris25
Created August 24, 2023 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helloris25/aa868ab5cf2951d8d8a69d602da7f3d6 to your computer and use it in GitHub Desktop.
Save helloris25/aa868ab5cf2951d8d8a69d602da7f3d6 to your computer and use it in GitHub Desktop.
simple memoize
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