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.
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.
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;
};
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With