6 ms·
(bit offtopic) but what about: module.exports = function leftpad (str, len, ch) { return Array(len).join(ch || ' ') + String(str); };
by vespakoen 10y ago
(bit offtopic) but what about:
module.exports = function leftpad (str, len, ch) {
return Array(len).join(ch || ' ') + String(str);
};
- rybosome 10y agoAlmost, but the existing code only pads when the str length is less than that of len.
- vespakoen 10y agoAhh you are right, all makes sense now, thanks!
- chvid 10y agoYou need to go something like: module.exports = function leftpad (str, len, ch) { return Array(Math.max(0, len - String(str).length)).join(ch || ' ') + String(str); }; Unfortunately we need to wrap str twice so maybe a one-liner is not quite in place.
- gsb 10y agoAlso, this doesn't support zero padding with ch=0.
- vespakoen 10y agoCool, I like the Math.max. Two liner then str = String(str);\n...
- deleted 10y ago[deleted]
- vespakoen 10y agoSo this I guess module.exports = function leftpad (str, len, ch) { str = String(str); if (ch === 0) { ch = '0'; } return Array(Math.max(0, len - str.length)).join(ch || ' ') + str; };
- chvid 10y agoAnd I did not notice the 0 check in the original code either :-D
- vespakoen 10y agoThe array + join is slower http://jsperf.com/leftpadtesting http://jsperf.com/leftpadtesting Repeat + slice is too http://jsperf.com/leftpad http://jsperf.com/leftpad
- deleted 10y ago[deleted]