Created
February 26, 2017 03:21
-
-
Save bbatliner/5d3629f756768c20a550590a4b2f7fab to your computer and use it in GitHub Desktop.
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
// Higher order memoize function | |
// fn returns a promise (not synchronous) | |
function memoize (fn) { | |
const lookup = {} | |
const memoized = function () { | |
const args = Array.from(arguments) | |
if (args in lookup) { | |
return lookup[args] | |
} | |
return fn.apply(this, args).then(val => { | |
lookup[args] = val | |
return val | |
}) | |
} | |
memoized.getLookup = () => lookup | |
return memoized | |
} | |
// Original fibonacci function | |
function fibonacci (n) { | |
if (n === 0 || n === 1) { | |
return Promise.resolve(n) | |
} | |
return Promise.all([fibonacci(n - 1), fibonacci(n - 2)]).then(results => results.reduce((a, b) => a + b, 0)) | |
} | |
// Memoized fibonacci function | |
const memoizedFibonacci = memoize(fibonacci) | |
// Redefine fibonacci to recursively use the memoized version (cache intermediate results) | |
function fibonacci (n) { | |
if (n === 0 || n === 1) { | |
return Promise.resolve(n) | |
} | |
return Promise.all([memoizedFibonacci(n - 1), memoizedFibonacci(n - 2)]).then(results => results.reduce((a, b) => a + b, 0)) | |
} | |
// See how the cached results grow with memoizedFibonacci.getLookup() | |
// e.g., | |
// memoizedFibonacci.getLookup() --> {} | |
// fibonacci(5).then(val => console.log(val)) --> 5 | |
// memoizedFibonacci.getLookup() --> {0: 0, 1: 1, 2: 1, 3: 2, 4: 3} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment