memoization in javascript

Memoization is a technique that helps to optimize recursive functions in JavaScript by caching previously computed results. This technique can be used to save time and computing resources when dealing with expensive computations.

Here is an example of memoization in JavaScript:

index.tsx
function fibonacci(n, cache) {
  cache = cache || {};
  if (cache[n]) return cache[n];
  if (n <= 1) return 1;
  return cache[n] = fibonacci(n - 1, cache) + fibonacci(n - 2, cache);
}
184 chars
7 lines

In this example, we use an object cache to store the previously computed results of fibonacci(n). The first time fibonacci(n) is called, the cache object will be undefined, so we initialize it as an empty object. We then check to see if cache[n] exists, which indicates that we've already computed the nth Fibonacci number. If it does, we return the cached value.

If cache[n] does not exist, we compute the nth Fibonacci number recursively using fibonacci(n - 1) and fibonacci(n - 2) and store the result in cache. Subsequent calls to fibonacci(n) with the same value of n will retrieve the cached value from cache rather than recomputing it, which makes the code faster and more efficient.

Here's an example of calling fibonacci function with memoization:

index.tsx
console.log(fibonacci(10)); // returns 89
console.log(fibonacci(20)); // returns 10946
console.log(fibonacci(30)); // returns 1346269
134 chars
4 lines

Note that the cache object is passed as an argument to fibonacci function so that it can be used by the recursive calls to fibonacci. By doing this, we isolate the caching behavior of fibonacci from other parts of our program and avoid any potential conflicts.

gistlibby LogSnag