DEV Community

vishal1025
vishal1025

Posted on

Memoization in JS at function level

I recently encountered an interesting problem wherein you need to achieve a simple memoization at a function level.

Explaining the problem first,

Let's suppose you have been given a function for summation of 2 numbers

add = (a, b) => {
 return a,b
}
Enter fullscreen mode Exit fullscreen mode

You have to write a function let's suppose memoize which receives a function

function memoize(func) {}
Enter fullscreen mode Exit fullscreen mode

Input to the problem

let mem = memoize(add);
console.log(mem(1,2)) => 3
console.log(mem(2,4)) => 6
console.log(mem(1,2)) => 3
Enter fullscreen mode Exit fullscreen mode

So, problem is you need to complete the memoize function to return the output but the catch is if the input params are already being computed then you don't need to compute them again

Solution

So, let's start revising some core concept of JS i.e every function is ultimately an object in JS,🧐🧐

Let's think how we can use this concept in our function memoize

function memoize(func) {

  // Since, we can have a property in objects, right?
  if(!memoize.preInputs) {
    memoize.preInputs = []
  }

return function() {
        for(let i = 0; i < memoize.preInputs.length; i++) {
          if((memoize.preInputs[i]['arg1'] === arguments[0] && 
            memoize.preInputs[i]['arg2'] === arguments[1]) || 
            (memoize.preInputs[i]['arg1'] === arguments[1] && 
            memoize.preInputs[i]['arg2'] === arguments[0])) {
            console.log('precomputed');
            return memoize.preInputs[i]['result'];
          } 
         }
         memoize.preInputs.push({
              arg1: arguments[0],
              arg2: arguments[1],
              result: func(arguments[0], arguments[1])
            });
         console.log('newly calculated');
         return memoize.preInputs[memoize.preInputs.length - 1].result;
        }
Enter fullscreen mode Exit fullscreen mode

Now, let's try using the output,
console.log(mem(1,2))
=> newly calculated
3
console.log(mem(3,4))
=> newly calculated
7
console.log(mem(1,2))
=> precomputed
3

So, that's it this is a one way by which you can achieve this, I am pretty much sure you can have other ways also

Bye!
Happy Coding !!😁😁😁

Top comments (0)