DEV Community

Cover image for Memorization in Javascript
 Rahul Gupta
Rahul Gupta

Posted on

Memorization in Javascript

Memoization is a programming technique that attempts to increase a function’s performance by caching its previously computed results.

Each time a memoized function is called, its parameters are used to index the cache.

If the data is present, then it can be returned, without executing the entire function. Otherwise, the function is executed

Code for Memorization:
`const memoizeAddition = () => {
let cache = {};
return (value) => {
if (value in cache) {
console.log("Fetching from cache");
return cache[value]; //Here, cache.value cannot be used as property name starts with the number which is not a

//valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
} else {
console.log("Calculating result");
let result = value + 20;
cache[value] = result;
return result;
}
};
};

// returned function from memoizAddition
const addition = memoizeAddition();
console.log(addition(20)); //output: 40 calculated
console.log(addition(20)); //output: 40 cached `

Top comments (0)