Created
June 28, 2020 12:44
-
-
Save capan/09c9c216812dc35ba25e302728567d5b to your computer and use it in GitHub Desktop.
JavaScript Memoization Example for Reducing the Time Complexity
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 veryComplexCalculation = (n) => (n * 10); | |
const memoize = (cb) => { | |
const cache = {}; | |
return (n) => { | |
if (n in cache) { | |
console.log('Retrieving from cache:', n); | |
return cache[n]; | |
} else { | |
console.log('Calculating ...'); | |
const result = cb(n); | |
cache[n] = result; | |
return result; | |
} | |
} | |
} | |
// (invoking) | |
const memoized = memoize(veryComplexCalculation); | |
try { | |
console.log('Returning Calculated value:', memoized(9)); // calculated | |
console.log('Returning Cached value:', memoized(9)); // cached | |
} catch (e) { | |
console.error('Error: ', e) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment