DEV Community

vishal1025
vishal1025

Posted on

3 2

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 !!😁😁😁

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay