Memoization is required because it optimizes the performance of slow or expensive functions by reducing the number of times they need to be executed.
For example, in financial calculations, if the same mathematical formula is used multiple times, memoization can be used to cache the result of the formula, reducing the calculation time and increasing the overall efficiency of the application.
Memoization is a technique in JavaScript where the result of a function is stored in the cache to avoid redundant computation when the function is called again with the same arguments.
The idea is to store the results of a function in a cache, keyed by its arguments, so that the next time the function is called with the same arguments, the result can be immediately retrieved from the cache instead of being recomputed.
Let's take an example, you are writing a program to calculate returns for your stock market application, At that time you can use memorization as follows.
function memoize(fn) {
const cache = {};
return function(...args) {
if (cache[args]) {
return cache[args];
}
const result = fn.apply(this, args);
cache[args] = result;
return result;
};
}
const returnsCalculator = memoize(function(principal, interest, years) {
if (years === 0) return principal;
return returnsCalculator(principal * (1 + interest), interest, years - 1);
});
const principal = 1000;
const interest = 0.05;
const years = 5;
console.log(returnsCalculator(principal, interest, years));
let's understand the above code: