Memoization is a programming technique that involves caching the results of function calls based on their input parameters. The idea behind memoization is that if a function is called with the same input parameters multiple times, the result can be cached and returned without the need to recompute it. This can improve the performance of the function and reduce the amount of redundant computations.
In JavaScript, memoization can be implemented using closures and objects to store the cached results. Here’s an example of how to implement memoization in JavaScript:
function fibonacci(n) {
if (n === 0 || n === 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key] === undefined) {
cache[key] = fn.apply(this, args);
}
return cache[key];
}
}
const memoizedFibonacci = memoize(fibonacci);
console.log(memoizedFibonacci(10)); // returns 55
console.log(memoizedFibonacci(10)); // returns 55 (from cache)
In this example, the fibonacci function calculates the nth number in the Fibonacci sequence recursively. The memoize function takes a function as an argument and returns a new function that memoizes the original function. The memoized function uses an object to store the cached results, with the input arguments as the key and the result as the value.
The memoized fibonacci function is created by passing the original fibonacci function to the memoize function. When the memoized fibonacci function is called, it first checks whether the result is already cached. If the result is not cached, the original fibonacci function is called with the input arguments and the result is cached before being returned. If the result is already cached, it is returned directly from the cache.
Memoization is a powerful technique for optimizing functions that are called frequently with the same input parameters. It can improve the performance of the function and reduce the amount of redundant computations. However, memoization should only be used for pure functions, where the output only depends on the input and has no side effects.