Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Last active January 6, 2024 08:48
Show Gist options
  • Save MarwanShehata/2f92b311dfd538e8c955b8a3fdca7c60 to your computer and use it in GitHub Desktop.
Save MarwanShehata/2f92b311dfd538e8c955b8a3fdca7c60 to your computer and use it in GitHub Desktop.
6. Basic Memoization Example from FrontEndMasters
const times10 = (num) => {
const a = num * 10;
return a;
};
console.log(`~~~~~~~~TASK 1~~~~~~~~`);
console.log(`times10 returns: ${times10(9)}`);
const cache = {};
const memoTimes10 = (n) => {
if (n in cache) {
console.log(`Fetchig from cache ${n}`);
return cache[n];
} else {
console.log(`Calculating result`);
let result = times10(n);
cache[n] = result;
return result;
}
};
console.log(`~~~~TASK 2~~~~~`);
console.log(`T2 calculated value: ${memoTimes10(9)}`);
console.log(`T2 cached value: ${memoTimes10(6)}`); //change it back to 9 to test it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment