Nuru Salihu Nuru Salihu - 1 month ago 6
Javascript Question

Override and rename prototype in javascript

I am asked a question today that took me by surprise . I know

string.repeat(number)
repeat string to the said numbers in javascript. Example.

"Father".repeat(3)


Should print


FatherFatherFather


I was asked to do the same thing but instead using
.repeat
, i should use my new method like
strRepeater
in such a way that.

"Father".strRepeater(3)


Should equal

"Father".repeat(3);


Please how do i do this ? Any help would be appreciated.

Answer

There are 3 options:

1) Creating an alias to the prototype:

String.prototype.strRepeater = String.prototype.repeat;

2) Creating a wrapper around the prototype:

String.prototype.strRepeater = function() {
  return this.repeat.apply(arguments);
};

3) Creating your own method:

String.prototype.strRepeater = function(times) {
  var res = "";
  for (var i = 0; i < times; i++) {
    res += this;
  }
  return res;
};
Comments