59. What is memoization in functional programming? Explain with the help of an example in JavaScript.
medium

Memoization is a technique used in functional programming that allows a function to cache its intermediate results, so that it does not need to re-compute them every time they are needed. This can significantly improve the performance of a program by reducing the number of times a function needs to be evaluated.


In JavaScript, memoization can be implemented using an object to store previously computed values. Here's an example of a simple recursive function that calculates the nth Fibonacci number, and how it can be optimized using memoization:

function fibonacci(n) {
  if (n <= 1) return n; // base case
  else return fibonacci(n-1) + fibonacci(n-2); // recursive case
}

const memo = {};

function fibonacciOptimized(n) {
  if (memo[n]) return memo[n]; // cache previously computed value
  const result = fibonacci(n); // compute result
  memo[n] = result; // store result in cache
  return result;
}

console.log(fibonacci(5)); // Output: 8
console.log(fibonacciOptimized(5)); // Output: 8

In the first implementation of fibonacci, the function is called recursively to compute each intermediate result, which can be slow for large values of n. In the second implementation, we use an object called memo to store previously computed values. The function first checks if the value it needs has already been calculated and stored in the cache. If so, it returns that value directly, without re-computing it. This can significantly improve the performance of the program for large values of n.