Created
June 28, 2018 00:39
-
-
Save juan-cortes/f45456e55b28086b195eb34bdac034f3 to your computer and use it in GitHub Desktop.
Extended example of closures in javascript, adding memoization to the mix
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
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