Skip to content

Instantly share code, notes, and snippets.

@SirSerje
Created November 10, 2021 16:13
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 SirSerje/5b6b4eba526e894fc4fcc977e1da277e to your computer and use it in GitHub Desktop.
Save SirSerje/5b6b4eba526e894fc4fcc977e1da277e to your computer and use it in GitHub Desktop.
Memo on a budget
const add = (a,b) => a+b;
function memo (fn) {
let args = [];
function result(a,b) {
let hasMemo = args.reduce((acc, i) => {
if(i.a === a && i.b === b) {
return i;
}
}, null);
if(hasMemo) {
console.log('has memo, return collected');
return hasMemo.result;
} else {
console.log('hasnot memo, calc new')
const result = fn(a,b);
args.push({a,b,result});
return result;
}
}
return result;
}
const memoizedAdd = memo(add);
console.log(memoizedAdd(1,2));
console.log(memoizedAdd(1,2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment