How to write a simple code of Memoization function in JavaScript ?
Memoization is a programming technique that we used to speed up functions and it can be used to do whenever we have an expensive function ( takes a long time to execute). It relies on the idea of cache {}. A cache is just a plain object. It reduces redundant function expression calls.
Let’s understand how to write a simpler code of the Memoization function in JS.
Example 1: In this example, we will see the inefficient way of writing a function that takes more time to compute.
Javascript
const square = (n) => {
let result = 0;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
return result;
}
console.log(square(10000006));
console.log(square(40));
console.log(square(5));
|
Output:
For this reason, to compute operation in less time for large, we use memoization.
There are two ways to do memoization:
- Function memoization
- Cache memoization
Slow function which takes a large time to compute using cache memoization.
Example 2: This example is used to find the Square of number
Javascript
const preValues = []
function square(n) {
if (preValues[n] != null ) {
return preValues[n]
}
let result = 0;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
preValues[n] = result;
return result;
}
console.log(square(50000));
console.log(square(5000));
console.log(square(500));
|
Output
2500000000
25000000
250000
Uses in Dynamic programming using cache memoization.
Example 3: This example is used to print Fibonacci sequence
Javascript
fib = (n, preValues = []) => {
if (preValues[n] != null )
return preValues[n];
let result;
if (n <= 2)
result = 1;
else
result = fib(n - 1, preValues) + fib(n - 2, preValues);
preValues[n] = result;
return result;
}
console.log(fib(100));
|
Output
354224848179262000000
Using memoizer i.e. it takes a function and then it has to return a function.
Example 4: This example shows memoization in Javascript
Javascript
const memoize = () => {
const results = {};
return (...args) => {
const argsKey = JSON.stringify(args);
if (!results[argsKey]) {
results[argsKey] = func(...args)
}
return results[argsKey];
};
};
const multiply = memoize((num1, num2) => {
let total = 0;
for (let i = 0; i < num1; i++) {
for (let j = 0; j < num1; j++) {
total += 1 *;
}
}
return total * num2;
});
console.log(multiply(500, 5000));
|
Output:
1250000000
Last Updated :
17 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...