Skip to content

Instantly share code, notes, and snippets.

@capan
Created June 28, 2020 12:44
Show Gist options
  • Save capan/09c9c216812dc35ba25e302728567d5b to your computer and use it in GitHub Desktop.
Save capan/09c9c216812dc35ba25e302728567d5b to your computer and use it in GitHub Desktop.
JavaScript Memoization Example for Reducing the Time Complexity
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