Created
September 14, 2020 19:19
-
-
Save munkacsitomi/804110dd4cde6dee3740de1044c3be16 to your computer and use it in GitHub Desktop.
Caching function calculation results
This file contains hidden or 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
function cached(fn) { | |
// Create an object to store the results returned after each function execution. | |
const cache = Object.create(null); | |
// Returns the wrapped function | |
return function cachedFn(str) { | |
// If the cache is not hit, the function will be executed | |
if (!cache[str]) { | |
let result = fn(str); | |
// Store the result of the function execution in the cache | |
cache[str] = result; | |
} | |
return cache[str]; | |
} | |
} | |
function computed(str) { | |
// Suppose the calculation in the funtion is very time consuming | |
console.log('bang'); | |
return 'a result'; | |
} | |
const cachedComputed = cached(computed); | |
cachedComputed('first'); | |
cachedComputed('first'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment