Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Last active January 6, 2024 09:47
Show Gist options
  • Save MarwanShehata/1249c43467ef74dc0f7304a8b5313373 to your computer and use it in GitHub Desktop.
Save MarwanShehata/1249c43467ef74dc0f7304a8b5313373 to your computer and use it in GitHub Desktop.
Memoization with closures from FrontEndMasters algo course
const memoizedClosureTimes10 = () => {
let cache = {};
return (n) => {
if (n in cache) {
console.log(`Fetching from cache: ${n}`);
return cache[n];
} else {
console.log(`Calculating result~~`);
let result = n * 10;
cache[n] = result;
return result;
}
};
};
// Making the argument n private to the function is to make it modular
// You can refer to it multiple times and every time you get a new cached version, make it n,m and make it more general
const memoClosureTimes10 = memoizedClosureTimes10(); // this just saves the return function to the variable
try {
console.log(`Task 3 calculated value: ${memoClosureTimes10(9)}`);
console.log(`Task 3 cached value: ${memoClosureTimes10(8)}`); // Check the function by changing this to 9
} catch (e) {
console.error(`Task 3: ${e}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment