1 year ago
#69627
Nesh
Functions as variable in Javascript
Following is my code of memoization which is working fine, output "Long Time"
once only -
Code -
function memoAdd80() {
let cache = {};
return (n) => {
if(n in cache) {
return cache[n];
}
console.log('Long Time');
const answer = n + 80;
cache[n] = answer;
return answer;
}
}
const memoized80 = memoAdd80();
console.log(memoized80(85)); // Long Time 165
console.log(memoized80(85)); // 165
console.log(memoized80(85)); // 165
Though, when writing like this - memoAdd80()(85)
this caching doesn't works.
console.log(memoAdd80()(85)); // Long Time 165
console.log(memoAdd80()(85)); // Long Time 165
console.log(memoAdd80()(85)); // Long Time 165
Let me know how can I directly use memoAdd80
instead of creating a memoized
variable first and then passing a value to the function.
javascript
optimization
functional-programming
memoization
0 Answers
Your Answer