Last active
May 14, 2016 15:20
-
-
Save louisremi/bb03bceaac428c85929d35323f4ea520 to your computer and use it in GitHub Desktop.
stupid memoize
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
function memoize(fn) { | |
var cache = {}; | |
// return a memoized version of the function | |
return function(arg) { | |
// intercept the argument | |
if ( !(arg in cache) ) { | |
// if it's not in cache, execute the original function and | |
// cache the result, using the argument as the cache key. | |
cache[arg] = fn.call(this, arg); | |
} | |
// now we're sure that the result is cached, so return it | |
return cache[arg]; | |
}; | |
} |
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
var nbExecutions = 0; | |
var square = function(n) { | |
nbExecutions++; | |
return n * n; | |
} | |
var squareMemoized = memoize(square); | |
squareMemoized(2); // === 4 | |
// nbExecutions === 1 | |
// cache is { '2': 4 } | |
squareMemoized(3); // === 9 | |
// nbExecutions === 2 | |
// cache is { '2': 4, '3': 9 } | |
// when the memoized function is executed with an argument that is already in | |
// the cache, the result is returned without executing the original function | |
squareMemoized(2); // === 4 | |
// nbExecutions === 2 | |
// cache is { '2': 4, '3': 9 } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment