Created
March 24, 2021 21:27
-
-
Save christianjuth/d3ed8fa1d3b33ff60a1bd05ec18c39cd to your computer and use it in GitHub Desktop.
Memo function
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 memo(fn) { | |
const dict = {} | |
let id | |
const perform = { calls: 0, memoHits: 0 } | |
return (...args) => { | |
perform.calls++ | |
clearTimeout(id) | |
id = setTimeout(() => { | |
console.log(`memo hit rate = ${perform.memoHits}/${perform.calls}`) | |
}, 1000) | |
const key = JSON.stringify(args) | |
if (dict[key] !== undefined) { | |
perform.memoHits++ | |
return dict[key] | |
} | |
const output = fn(...args) | |
dict[key] = output | |
return output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Memo function and log performance info