Last active
February 26, 2017 03:20
-
-
Save bbatliner/0311ae735a7f7c9506d170a08d065edd to your computer and use it in GitHub Desktop.
A simple demonstration of memoization for the Fibonacci function
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 | |
function memoize (fn) { | |
const lookup = {} | |
const memoized = function () { | |
const args = Array.from(arguments) | |
if (args in lookup) { | |
return lookup[args] | |
} | |
return (lookup[args] = fn.apply(this, args)) | |
} | |
memoized.getLookup = () => lookup | |
return memoized | |
} | |
// Original fibonacci function | |
function fibonacci (n) { | |
if (n === 0 || n === 1) { | |
return n | |
} | |
return fibonacci(n - 1) + fibonacci(n - 2) | |
} | |
// 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 n | |
} | |
return memoizedFibonacci(n - 1) + memoizedFibonacci(n - 2) | |
} | |
// See how the cached results grow with memoizedFibonacci.getLookup() | |
// e.g., | |
// memoizedFibonacci.getLookup() --> {} | |
// fibonacci(5) --> 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