Last active
May 14, 2016 16:57
-
-
Save louisremi/3de05c08d13aadc1451b6e94cad52b98 to your computer and use it in GitHub Desktop.
Nested map
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
// 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