Memoized function implementation in JS. How does it work?

281 Views Asked by At

I was in an interview recently where I was asked a coding question in JavaScript. The question was regarding the implementation of memoization of a function. I figured that we need to store the arguments and result for implementing this, and I suggested localStorage as I couldn't think of another way to store the arguments that is not limited to the scope of the function(I am an amateur at JS). When I asked ChatGPT for the solution to this problem, it suggested the following -

function memoize(func) {
  const cache = new Map(); // Use a Map to store cached results

  return function (...args) {
    const key = JSON.stringify(args); // Create a unique key based on function arguments

    if (cache.has(key)) {
      // If the result is cached, return it
      return cache.get(key);
    } else {
      // Otherwise, compute the result and cache it
      const result = func(...args);
      cache.set(key, result);
      return result;
    }
  };
}

// Example function to be memoized
function expensiveFunction(n) {
  console.log(`Computing for ${n}`);
  return n * 2;
}

// Create a memoized version of the expensive function
const memoizedExpensiveFunction = memoize(expensiveFunction);

console.log(memoizedExpensiveFunction(5)); // Computes and caches for 5
console.log(memoizedExpensiveFunction(5)); // Returns cached result for 5
console.log(memoizedExpensiveFunction(10)); // Computes and caches for 10
console.log(memoizedExpensiveFunction(10)); // Returns cached result for 10

But, in this, the Map function is used to defined inside the function and logically, it must be limited to the scope of the memoize function, and not persist on consecutive function calls.

I tried running this code, and it works. But, I cannot wrap my head around why it works. Please help me out by either explaining how this works or by providing links to the relevant documentation for this. The documentation that I refererred doesn't mention anything regarding it's scope. Also, do let me know if there is any other way to implement memoization in JS(the interviewer mentioned something like 'use try data structure' and I don't know what that means).

1

There are 1 best solutions below

0
brk On

it must be limited to the scope of the memoize function, and not persist on consecutive function calls.

The answer to your question is this line

const memoizedExpensiveFunction = memoize(expensiveFunction);.

Here you are creating a instance of the function and calling the function which is returned by memoize function. Now the function return by memoize also have access to variable defined outside it's scope (closure). So whenever you are calling memoizedExpensiveFunction it can see the variable cache