Skip to content

Instantly share code, notes, and snippets.

@christianjuth
Created March 24, 2021 21:27
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 christianjuth/d3ed8fa1d3b33ff60a1bd05ec18c39cd to your computer and use it in GitHub Desktop.
Save christianjuth/d3ed8fa1d3b33ff60a1bd05ec18c39cd to your computer and use it in GitHub Desktop.
Memo function
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
}
}
@christianjuth
Copy link
Author

Memo function and log performance info

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment