Last active
August 29, 2015 14:15
-
-
Save Syrup-tan/6664a9ca52eacffdc59d to your computer and use it in GitHub Desktop.
Memoization function for ECMAScript
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
// Get the nth fibonacci number, starting from fib(0) == 1 | |
var fib = Memoize(function(n) { | |
if (n == 0) return 1; | |
if (n == 1) return 1; | |
return fib(n - 1) + fib(n - 2); | |
}); | |
// Define the Memoize function | |
function Memoize(f) { | |
// Results of previous calls | |
var results = {}; | |
// Return the memoized function | |
return function() { | |
// Need to use JSON.stringify because; | |
// Symbol.for([1,2]) === Symbol.for('1,2') | |
// results[[1,2]] === results['1,2'] | |
var key = JSON.stringify(arguments); | |
// Return the result if we have it cached | |
return results[key] || ( | |
// Otherwise calculate it, cache it, then return it | |
results[key] = f.apply(null, arguments) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment