Skip to content

Instantly share code, notes, and snippets.

@munkacsitomi
Created September 14, 2020 19:19
Show Gist options
  • Save munkacsitomi/804110dd4cde6dee3740de1044c3be16 to your computer and use it in GitHub Desktop.
Save munkacsitomi/804110dd4cde6dee3740de1044c3be16 to your computer and use it in GitHub Desktop.
Caching function calculation results
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