Created
November 10, 2021 16:13
-
-
Save SirSerje/5b6b4eba526e894fc4fcc977e1da277e to your computer and use it in GitHub Desktop.
Memo on a budget
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
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