Last active
September 16, 2023 14:39
-
-
Save chicho69-cesar/92aa11ae9c52522ff35632b48eea357d to your computer and use it in GitHub Desktop.
JavaScript memoization
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
// 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