DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 115

The task is to implement memoizeOne().

The boilerplate code

function memoizeOne(func, isEqual) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

memoizeOneis a lightweight memoization function that caches only the most recent function call result.

Previous arguments, result and context have to be stored. And also need to track if it has been called (subsequent calls should return cached value)

lastArgs = undefined
lastResult = undefined;
lastThis = undefined;
hasBeenCalled = false;
Enter fullscreen mode Exit fullscreen mode

On the first call, mark that the function has been called, store arguments and context, cache and return the result.

if(!hasBeenCalled) {
  hasBeenCalled = true;
  lastArgs = args;
  lastThis = this;
  lastResult = func.apply(this, args);
  return lastResult;
}
Enter fullscreen mode Exit fullscreen mode

Check if the next function call is the same as the previous

const equalityCheck = isEqual || defaultIsEqual;
Enter fullscreen mode Exit fullscreen mode

Also, ensure that the context of execution is the same

if(this === lastThis && equalityCheck(args, lastArgs)) {
  return lastResult;
}
Enter fullscreen mode Exit fullscreen mode

The function to check each function call.

function defaultIsEqual(args1, args2) {
Enter fullscreen mode Exit fullscreen mode

If the length of both arguments are not equal, the functions are not

 if(args1.length !== args2.length) {
    return false;
  }
Enter fullscreen mode Exit fullscreen mode

Check each argument strictly

 for(let i = 0; i < args1.length; i++) {
    if(args1[i] !== args2[i]) {
      return false;
    }
  }

  return true;
Enter fullscreen mode Exit fullscreen mode

The final code

function memoizeOne(func, isEqual) {
  // your code here
  let lastArgs = undefined;
  let lastResult = undefined;
  let hasBeenCalled = false;
  let lastThis = undefined;

  return function (...args) {
    if(!hasBeenCalled) {
      hasBeenCalled = true;
      lastArgs = args; 
      lastThis = this;
      lastResult = func.apply(this, args);
      return lastResult
    }

    const equalityCheck = isEqual || defaultIsEqual;

    if(this ===lastThis && equalityCheck(args, lastArgs)) {
      return lastResult;
    }

    lastArgs = args;
    lastThis = this;
    lastResult = func.apply(this, args);
    return lastResult;
  }
}

function defaultIsEqual(args1, args2) {
  if(args1.length !== args2.length) {
    return false;
  }

  for(let i = 0; i < args1.length; i++) {
    if(args1[i] !== args2[i]) {
      return false;
    }
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)