DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 45

The task is to implement myNew function to return an object just like the new constructor.

const myNew = (constructor, ...args) => {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

How does the new operator work? It creates a new empty object, sets the prototype of that object to the constructor's prototype, calls the constructor function, and returns the object the constructor returns or the newly created one.

If the constructor is not a function, throw an error

if (typeof constructor !== 'function') {
    throw new TypeError('myNew: first argument must be a constructor function');
  }
Enter fullscreen mode Exit fullscreen mode

Create the new object to be returned if the constructor does not return one

const obj = Object.create(constructor.prototype);
Enter fullscreen mode Exit fullscreen mode

Call the constructor with "this" set to the new object

const result = constructor.apply(obj, args);
Enter fullscreen mode Exit fullscreen mode

If the constructor returns an object (or function), return it. Otherwise, return the new function

return (result !== null && (typeof result === 'object' || typeof result === 'function')) 
    ? result 
    : obj;
Enter fullscreen mode Exit fullscreen mode

The final code

const myNew = (constructor, ...args) => {
  // your code here
  if(typeof constructor !== 'function') {
    throw new TypeError('myNew: first argumant must be a function')
  }
  const obj = Object.create(constructor.prototype);

  const result = constructor.apply(obj, args)

  return (result !== null && (typeof result === 'object' || typeof result === 'function'))
  ? result : obj;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)