Last active
January 9, 2017 20:59
-
-
Save johnwalley/86a85437b74ffccc06699fbeb47ace51 to your computer and use it in GitHub Desktop.
Memoization
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
function memoize(func) { | |
var cache = {}; | |
return function(n) { | |
if (cache.hasOwnProperty(n)) { | |
return cache[n]; | |
} | |
var result = func(n); | |
cache[n] = result; | |
return result; | |
} | |
} |
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
var cache = {}; | |
function fibonacci(n) { | |
if (cache.hasOwnProperty(n)) { | |
return cache[n]; | |
} | |
if (n <= 1) { | |
return 1; | |
} else { | |
var result = fibonacci(n - 1) + fibonacci(n - 2); | |
cache[n] = result; | |
return result; | |
} | |
}; |
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
function memoize(func, hash) { | |
var cache = {}; | |
return function() { | |
var key = hash(arguments); | |
if (cache.hasOwnProperty(key)) { | |
return cache[key]; | |
} | |
var result = func(key); | |
cache[key] = result; | |
return result; | |
} | |
} | |
var memoizedFibonacci = memoize(fibonacci, args => args[0); |
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
function fibonacci(n) { | |
if (n <= 1) { | |
return 1; | |
} | |
return fibonacci(n - 1) + fibonacci(n - 2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment