Memoization in JS at function level

vishal1025 profile image vishal1025 ・2 min read

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


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])) {
            return memoize.preInputs[i]['result'];
              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,
=> newly calculated
=> newly calculated
=> precomputed

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

Happy Coding !!😁😁😁


Editor guide