News for hackers. Stuff that matters.
Re:I've Just Liberated My Modules by vespakoen on Tuesday March 22, 2016 @08:06PM (#11340989)
(bit offtopic) but what about:

module.exports = function leftpad (str, len, ch) { return Array(len).join(ch || ' ') + String(str); };

Re:I've Just Liberated My Modules by rybosome on Tuesday March 22, 2016 @08:28PM (#11341115)
Almost, but the existing code only pads when the str length is less than that of len.
Re:I've Just Liberated My Modules by vespakoen on Tuesday March 22, 2016 @08:39PM (#11341182)
Ahh you are right, all makes sense now, thanks!
Re:I've Just Liberated My Modules by chvid on Tuesday March 22, 2016 @09:28PM (#11341428)
You 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.
Re:I've Just Liberated My Modules by vespakoen on Tuesday March 22, 2016 @10:16PM (#11341646)
The array + join is slower

http://jsperf.com/leftpadtesting

Repeat + slice is too

http://jsperf.com/leftpad

Re:I've Just Liberated My Modules by vespakoen on Tuesday March 22, 2016 @10:00PM (#11341570)
So 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; };

Re:I've Just Liberated My Modules by vespakoen on Tuesday March 22, 2016 @09:53PM (#11341543)
Cool, I like the Math.max. Two liner then str = String(str);\n...
Re:I've Just Liberated My Modules by chvid on Tuesday March 22, 2016 @10:01PM (#11341579)
And I did not notice the 0 check in the original code either :-D
Re:I've Just Liberated My Modules by gsb on Tuesday March 22, 2016 @09:52PM (#11341534)
Also, this doesn't support zero padding with ch=0.