Skip to content

Instantly share code, notes, and snippets.

@fob2257
Created November 1, 2019 19:57
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 fob2257/a1c6dff17e19280315e001606e220206 to your computer and use it in GitHub Desktop.
Save fob2257/a1c6dff17e19280315e001606e220206 to your computer and use it in GitHub Desktop.
const memo = fn => {
const cache = {};
return function () {
// arguments belongs to our returned anonymous function
// fn is the function we wish to apply this arguments
const key = JSON.stringify(arguments);
if (!!!cache[key]) cache[key] = fn.apply(null, arguments);
console.log({ cache });
return cache[key];
};
};
const fibo = memo(function innerFn(n) {
if (n < 2) return 1;
return fibo(n - 2) + fibo(n - 1);
});
fibo(10);
// now fibonacci of 10 is "cached"
fibo(10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment