Skip to content

Instantly share code, notes, and snippets.

@panicoenlaxbox
Last active February 27, 2020 20:44
Show Gist options
  • Save panicoenlaxbox/09d0bae1a9897fe231765fbaf5ce9ff4 to your computer and use it in GitHub Desktop.
Save panicoenlaxbox/09d0bae1a9897fe231765fbaf5ce9ff4 to your computer and use it in GitHub Desktop.
function memoize(fn: any): any {
console.log('memoize');
const cache = {};
return function () {
const key: string = JSON.stringify(arguments);
if (cache[key]) {
console.log(`${key} found in cache`);
return cache[key];
}
else {
console.log(`${key} not found in cache`);
const value = fn.apply(this, arguments);
cache[key] = value;
return value;
}
};
}
const factorial = memoize(function (n: number): number {
console.log(`working for factorial(${n})`);
if (n === 1) {
return 1
};
return n * factorial(n - 1);
});
console.log(factorial(3));
// memoize
// {"0":3} not found in cache
// working for factorial(3)
// {"0":2} not found in cache
// working for factorial(2)
// {"0":1} not found in cache
// working for factorial(1)
// 6
console.log(factorial(3));
// {"0":3} found in cache
// 6
console.log(factorial(4));
// {"0":4} not found in cache
// working for factorial(4)
// {"0":3} found in cache
// 24
console.log(factorial(3));
// {"0":3} found in cache
// 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment