Created
August 19, 2016 06:28
-
-
Save stefanfrede/ab3d0fb6bf030a6d96a57061dffb00aa to your computer and use it in GitHub Desktop.
Use a lookup table for recursive functions to look up results to avoid recalculation
This file contains hidden or 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
const memoized = (fn) => { | |
const lookupTable = {}; | |
return function (...args) { | |
const key = JSON.stringify(this, args); | |
return lookupTable[key] || (lookupTable[key] = fn.apply(this, args)); | |
} | |
} | |
/** | |
* Example | |
*/ | |
const fibonacci = (n) => | |
n < 2 | |
? n | |
: fibonacci(n - 2) + fibonacci(n - 1); | |
[0,1,2,3,4,5,6,7,8].map(fibonacci) | |
//=> [0,1,1,2,3,5,8,13,21] | |
// Time it | |
s = (new Date()).getTime() | |
fibonacci(45) | |
( (new Date()).getTime() - s ) / 1000 | |
//=> 15.194 | |
const fastFibonacci = memoized( | |
(n) => | |
n < 2 | |
? n | |
: fastFibonacci(n - 2) + fastFibonacci(n - 1) | |
); | |
fastFibonacci(45) | |
//=> 1134903170 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment