Created
October 16, 2016 16:46
-
-
Save hackash/97ba4bb8a191d2c51b437acdb50614ab to your computer and use it in GitHub Desktop.
Caching function return value in javascript
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 multiply(a, b, c) { | |
if (!multiply.cache) { | |
multiply.cache = {}; | |
} | |
var cachedArgs = JSON.stringify(arguments); | |
if (multiply.cache[cachedArgs]) { | |
return multiply.cache[cachedArgs]; | |
} | |
return multiply.cache[cachedArgs] = a * b * c; | |
} | |
console.log(multiply(10, 10, 10)); // output 1000 | |
console.log(multiply(10, 10, 10)); // output 1000 (cached) | |
console.log(multiply(10, 10, 10)); // output 1000 (cached) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment