Skip to content

Instantly share code, notes, and snippets.

@jscodelover
Created February 4, 2020 12:34
Show Gist options
  • Save jscodelover/5962aa29f98afb13821df0487b388ca6 to your computer and use it in GitHub Desktop.
Save jscodelover/5962aa29f98afb13821df0487b388ca6 to your computer and use it in GitHub Desktop.
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('time consuming calculation');
return 'a result'
}
const computed_result = cached(computed);
console.log(computed_result('ss'));
// time consuming calculation
// a result
console.log(computed_result('ss'));
// a result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment