DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 101

The task is to implement function.prototype.call().

The boilerplate code

Function.prototype.mycall = function(thisArg, ...args) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

function.prototype.call is useful when the this of a function is to be altered. First, ensure that this is callable

 if(typeof this !== "function") {
    throw new TypeError("mycall must be a function");
  }
Enter fullscreen mode Exit fullscreen mode

Handle null/undefined by converting them to the global object.

 if (thisArg === null || thisArg === undefined) {
    thisArg = globalThis;
  }
Enter fullscreen mode Exit fullscreen mode

If the arguments are primitive, transform them to objects

else {
        thisArg = Object(thisArg);
  }
Enter fullscreen mode Exit fullscreen mode

Create a unique property to avoid collisions

const fnKey = Symbol("fn");
Enter fullscreen mode Exit fullscreen mode

Temporarily attach function to thisArg

thisArg[fnKey] = this
Enter fullscreen mode Exit fullscreen mode

Invoke function with the provided arguments

 const result = thisArg[fnKey](...args);
Enter fullscreen mode Exit fullscreen mode

Clean up after execution

delete thisArg[fnKey];
Enter fullscreen mode Exit fullscreen mode

Return the result

return result;
Enter fullscreen mode Exit fullscreen mode

The final code

Function.prototype.mycall = function(thisArg, ...args) {
  // your code here
  if(typeof this !== "function") {
    throw new TypeError("mycall must be a function");
  }

  if(thisArg === null || thisArg === undefined) {
    thisArg = globalThis;
  } else {
    thisArg = Object(thisArg);
  }

  const fnKey = Symbol("fn");

  thisArg[fnKey] = this;

  const result = thisArg[fnKey](...args);

  delete thisArg[fnKey];

  return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)