Search code examples
javascriptprototype

Implementing a Number.prototype.loop(callback)


How to pass a reference of an argument, originally passed to a prototype function, on to a callback function which, too, is passed to the same prototype function?

The objective of the implementation is to loop for the value of the Number by executing the callback function.

Number.prototype.loop = function(index, callback) {
  return Array(this).fill(0).forEach((e, i) => {
    if(callback)
      callback();
  });
};

var num = 3;

num.loop(index, function(){
  console.log(index);
});

Solution

Apparently, the reference to index is supposed to be passed directly to the callback function in order to indicate that the actual index property of the Array in the prototype function is to be passed to the callback function.

Number.prototype.loop = function(callback) {
  return Array(this).fill(0).forEach((e, i) => {
    if(callback)
      callback(i);
  });
};

var num = 3;

num.loop((index) => {
  console.log(index);
});

Solution

  • There are 2 errors.

    1. Pass the index i to callback in Number.prototype.loop function instead of the caller:

      • num.loop(index, function(index) {num.loop(function(index) {
      • Number.prototype.loop = function(index, callback) {Number.prototype.loop = function(callback) {
      • callback();callback(i);
    2. Pass the numerical value of this instead of the instance itself to the Array constructor:

      • Array(this)Array(this.valueOf())

    Number.prototype.loop = function(callback) {
      var num = this.valueOf();
      return Array(num).fill(0).forEach((e, i) => {
        if (callback)
          callback(i);
      });
    };
    
    var num = 3;
    
    num.loop(function(index) {
      console.log(index);
    });