technical,
programming,
JavaScript13:26 -0400
Improved versions of
left-padShorter version (removed unneeded variable, and change to for loop: 9 lines of code instead of 11):
module.exports = leftpad;
function leftpad (str, len, ch) {
str = String(str);
if (!ch & ch !== 0) ch = ' ';
for (len -= str.length; len > 0; len--) {
str = ch + str;
}
return str;
}
Faster version (only perform O(log n) concatenations, where n is the number of characters needed to pad to the right length):
module.exports = leftpad;
function leftpad (str, len, ch) {
str = String(str);
if (!ch & ch !== 0) ch = ' ';
ch = String(ch);
len -= str.length;
while (len > 0) {
if (len & 1) {
str = ch + str;
}
len >>>= 1;
ch += ch;
}
return str;
}
ES6 version (which may be faster if
String.prototype.repeat is implemented natively):
module.exports = leftpad;
function leftpad (str, len, ch) {
str = String(str);
if (!ch & ch !== 0) ch = ' ';
ch = String(ch);
len -= str.length;
if (len > 0) str = ch.repeat(len) + str;
return str;
}
Of course, you could combine the last two by detecting whether String.prototype.repeat is defined:
module.exports = String.prototype.repeat ?
function leftpad (str, len, ch) {
str = String(str);
if (!ch & ch !== 0) ch = ' ';
ch = String(ch);
len -= str.length;
if (len > 0) str = ch.repeat(len) + str;
return str;
}
:
function leftpad (str, len, ch) {
str = String(str);
if (!ch & ch !== 0) ch = ' ';
ch = String(ch);
len -= str.length;
while (len > 0) {
if (len & 1) {
str = ch + str;
}
len >>>= 1;
ch += ch;
}
return str;
}
As with the original left-pad, this code is released under the
WTFPL.
(See also
pad-left, which uses another dependency (by the same author) for repeating strings)
0 Comments