Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Created October 24, 2015 03:40
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 kevincennis/c9bff435ea700e15c8cd to your computer and use it in GitHub Desktop.
Save kevincennis/c9bff435ea700e15c8cd to your computer and use it in GitHub Desktop.
Generic Memoize
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