Today I was at job interview - and I had been presented with a task. I have never encoutered such a function, so there it is:
Write down a function which after triggering like this:
console.log('hello'.repeatify(3))
returns
hellohellohello
I was trying to create an empty object and append a method repeatify, however i just don't know how to trigger it just with 'hello'.
Maybe i should change console.log method?
Thanks for the help :)
Wasn't that really hard. You have to make a new function for String.prototype
and use repeat()
function to multiply given string by given argument.
String.prototype.repeatify = function(count){ return this.repeat(count); }; console.log('hello'.repeatify(3))
You can create your own prototype methods for every object, but you shouldn't do it with native objects:
String.prototype.repeatify = function(num) { return this.repeat(num); } console.log('hello'.repeatify(3));
String.prototype.repeatify = function(amount)
{
var endString = "";
for(var i = 0; i < amount; ++i)
{
endString += this;
}
return endString;
}
Just modify String's prototype object:
String.prototype.repeatify = function (A) {
var i = 1;
var a = this;
while (i++ < A) {
a += this;
}
return a;
}
console.log('hello'.repeatify(3));
// outputs hellohellohello
There are mixed feelings on modifying the prototype of built in objects. I have both that it is just fine and that it is a bad practice. Personally I try to avoid it and prefer defining a standalone function to modifying the prototype of something I didn't create.
repeatify
String.prototype.repeatify = String.prototype.repeatify || function (times = 1) {
// ES5 this
return [...``.padStart(times, ` `)].map((item, i) => item = this).join(``);
};
`abx`.repeatify(3);
// "abxabxabx"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.