Created
October 24, 2015 03:40
-
-
Save kevincennis/c9bff435ea700e15c8cd to your computer and use it in GitHub Desktop.
Generic 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 ) { | |
const map = new Map(); | |
const key = Symbol('key'); | |
return function() { | |
let item = map; | |
let cached = false; | |
for ( let i = 0; i < arguments.length; ++i ) { | |
let cache = item.get( arguments[ i ] ); | |
if ( !cache ) { | |
item.set( arguments[ i ], new Map() ); | |
item = item.get( arguments[ i ] ); | |
cached = false; | |
continue; | |
} | |
item = cache; | |
cached = true; | |
} | |
if ( cached ) { | |
return item.get( key ); | |
} | |
let result = fn.apply( this, arguments ); | |
item.set( key, result ); | |
return result; | |
} | |
} | |
function loop( fn, n ) { | |
let v; | |
for ( let i = 0; i < n; ++i ) { | |
v = fn( i ); | |
} | |
return v; | |
} | |
let mem = memoize( loop ); | |
console.log( mem( Math.sqrt, 1e9 ) ); // slow | |
console.log( mem( Math.sqrt, 1e9 ) ); // fast! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment