Skip to content

Instantly share code, notes, and snippets.

@louisremi
Last active May 14, 2016 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisremi/3de05c08d13aadc1451b6e94cad52b98 to your computer and use it in GitHub Desktop.
Save louisremi/3de05c08d13aadc1451b6e94cad52b98 to your computer and use it in GitHub Desktop.
Nested map
// a memoizer that works with functions that receive two arguments
// of any type (can be generalized to accept more arguments)
function memoize(fn) {
// The first level of our nested-cache
var cacheLevel1 = new Map();
return function(arg1, arg2) {
// Let's check the cache, using one argument at each level
if ( !cacheLevel1.has(arg1) ) {
// and create nested maps as we need them
const cacheLevel2 = new Map();
cacheLevel2.set(arg2, fn.call( this, arg1, arg2 ));
cacheLevel1.set(arg1, cacheLevel2);
} else if ( !cacheLevel1.get(arg1).has(arg2) ) {
cache.get(arg1).set(arg2, fn.call( this, arg1, arg2 ));
}
return cache.get(arg1).get(arg2);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment