So I think this ...
function stringRepeat(str, num) {
num = Number(num);
var result = '';
while (true) {
if (num & 1) { // (1)
result += str;
}
num >>>= 1; // (2)
if (num <= 0) break;
str += str;
}
return result;
}[Found @ ②ality – JavaScript and more]... (though nifty and nice code) can be replaced by:
function stringRepeat(str, num) {
return Array( (num || 1) + 1 ).join(str);
}Where
num || 1 ensures that the initial string is always returned, even if num is not passed in the method call.
1 opmerking:
We now have String.prototype.repeat
Een reactie posten