Reputation: 4928
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.
Upvotes: 9
Views: 1681
Reputation: 35491
There are 3 options:
Creating an alias to the prototype:
String.prototype.strRepeater = String.prototype.repeat;
Creating a wrapper around the prototype:
String.prototype.strRepeater = function() {
return this.repeat.apply(this, arguments);
};
Creating your own method:
String.prototype.strRepeater = function(times) {
var res = "";
for (var i = 0; i < times; i++) {
res += this;
}
return res;
};
Upvotes: 14
Reputation: 2938
While the other answers adding to the prototype are completely correct, they're also a bad habit to get into.
If adding anything to a prototype you should be using Object.defineProperty()
so it doesn't appear as a member of the method (ie, a for...in
loop will show up members, but not when added properly).
While this isn't a requirement for the String prototype, it's always a bad idea to get into bad habits and then wonder why things aren't working correctly later...
So the safe way to add the method is:
Object.defineProperty(String.prototype, "strRepeater", {
value: function(number) {
return this.repeat(number)
}
};
Or to be even more safe:
if (!String.prototype["strRepeater"]) {
Object.defineProperty(String.prototype, "strRepeater", {
value: function(number) {
return this.repeat(number)
}
};
}
On a technical note, this sets it with the defaults of enumerator: false
, configurable: false
and writeable: false
- which translates to "no, you can't list me, delete me, or change me".
Object.defineProperty on MDN.
Upvotes: 7
Reputation: 5546
Try this:
String.prototype.strRepeater = function(number) {
return this.repeat(number)
};
console.log("Father".strRepeater(3));
Explanations:
String.prototype.strRepeater
add your function to the String objectthis.repeat(number)
will call the repeat built-in function with your current string inthis
with number as paramreturn
returns the result of .repeat()
outside strRepeater()
Upvotes: 5