Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created October 4, 2016 22:08
Show Gist options
  • Select an option

  • Save gkucmierz/d04ca16956ca17486fc13e55727608f8 to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/d04ca16956ca17486fc13e55727608f8 to your computer and use it in GitHub Desktop.
Advanced memoization using references for any number of arguments - codewars
function memoize(func) {
let mem = {};
return (...args) => {
let dest = args.reduce((mem, arg) => {
mem.args = mem.args || [];
mem.mems = mem.mems || [];
let idx = mem.args.indexOf(arg);
let obj;
if (idx === -1) {
obj = {};
mem.args.push(arg);
mem.mems.push(obj);
} else {
obj = mem.mems[idx];
}
return obj;
}, mem);
if (!('res' in dest)) {
dest.res = func.apply(this, args);
}
return dest.res;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment