Skip to content

Instantly share code, notes, and snippets.

@juan-cortes
Created June 28, 2018 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juan-cortes/f45456e55b28086b195eb34bdac034f3 to your computer and use it in GitHub Desktop.
Save juan-cortes/f45456e55b28086b195eb34bdac034f3 to your computer and use it in GitHub Desktop.
Extended example of closures in javascript, adding memoization to the mix
function powerOfNFactory(power){
var counter = 0;
var cache = {};
return function generatedFunction(subject){
counter++;
console.log(`Dyanmic Power of ${power} called ${counter} time/s`);
if (cache[subject] === undefined) {
cache[subject] = Math.pow(subject, power);
} else {
console.log("Cached!");
}
return cache[subject];
}
}
var powerOf2 = powerOfNFactory(2);
var powerOf3 = powerOfNFactory(3);
powerOf2(2); // Returns 4, logs "Dyanmic Power of 2 called 1 time/s"
powerOf2(2); // Returns 4, logs "Dyanmic Power of 2 called 2 time/s" "Cached!"
powerOf3(3); // Returns 27, logs "Dyanmic Power of 3 called 1 time/s"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment