Last active
February 27, 2020 20:44
-
-
Save panicoenlaxbox/09d0bae1a9897fe231765fbaf5ce9ff4 to your computer and use it in GitHub Desktop.
Memoize in Typescript from http://inlehmansterms.net/2015/03/01/javascript-memoization/
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: 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