Last active
January 6, 2024 09:47
-
-
Save MarwanShehata/1249c43467ef74dc0f7304a8b5313373 to your computer and use it in GitHub Desktop.
Memoization with closures from FrontEndMasters algo course
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 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