Skip to content

Instantly share code, notes, and snippets.

@chicho69-cesar
Last active September 16, 2023 14:39
Show Gist options
  • Save chicho69-cesar/92aa11ae9c52522ff35632b48eea357d to your computer and use it in GitHub Desktop.
Save chicho69-cesar/92aa11ae9c52522ff35632b48eea357d to your computer and use it in GitHub Desktop.
JavaScript memoization
// memoization
const memo = (fn) => {
const memory = {}
return (key) => {
if (memory[key]) {
console.log('Extracting of the memory')
return memory[key]
}
console.log('Computed')
memory[key] = fn(key)
return memory[key]
}
}
const fn = memo((iterator) => {
let total = 1
for (let i = 0; i < iterator; i++) {
total = total * iterator
}
return total
})
console.time('Sin memo')
fn(5000000)
fn(5010000)
fn(5020000)
fn(5030000)
fn(5040000)
console.timeEnd('sin memo')
console.time('Con memo')
fn(5000000)
fn(5010000)
fn(5020000)
fn(5030000)
fn(5040000)
console.timeEnd('con memo')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment