Memoization is a technique used in programming to optimize the performance of a function by caching its previously computed results. This technique is used to avoid repeating expensive calculations and instead use the cached results.
Here's an example of how to implement memoization in JavaScript:
javascriptCopyfunction memoize(func) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = func.apply(this, args);
cache[key] = result;
return result;
};
}
function fibonacci(n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
const memoizedFibonacci = memoize(fibonacci);
console.log(memoizedFibonacci(10)); // 55
console.log(memoizedFibonacci(10)); // 55 (cached result)
In this example, the memoize
the function takes a function func
as its argument and returns a new function that wraps the original function with memoization logic.
The wrapped function first checks if the result of the current arguments is already cached in the cache
object. If it is, it returns the cached result. Otherwise, it calls the original function with the current arguments, caches the result, and returns it.
The fibonacci
function is a recursive function that calculates the nth number in the Fibonacci sequence. When we call memoizedFibonacci(10)
for the first time, it calculates the result using recursion and caches it. When we call it again with the same argument, it retrieves the cached result from the cache
object instead of recalculating it.