Skip to content

Instantly share code, notes, and snippets.

@hackash
Created October 16, 2016 16:46
Show Gist options
  • Save hackash/97ba4bb8a191d2c51b437acdb50614ab to your computer and use it in GitHub Desktop.
Save hackash/97ba4bb8a191d2c51b437acdb50614ab to your computer and use it in GitHub Desktop.
Caching function return value in javascript
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