News for hackers. Stuff that matters.
Re:I've Just Liberated My Modules by ars on Wednesday March 23, 2016 @02:45AM (#11342578)
> Feel free to show a smaller implementation that's more efficient.

How's this:

  function leftpad (str, len, ch) {
    ch = (len -= str.length) <= 0 ? '' : !ch && ch !== 0 ? ' ' : String(ch);

    while (--len > 0) ch += ch[0];
 
    return ch + String(str);
  }
No local variables, less manipulation of the input string, the string grows at the tail which is more efficient, and the code is much shorter.

(With a bit of work you can use the longer ch string that is built to reduce the number of string appends even more by appending multiple characters at once. Although probably not worth it for this function.)

Re:I've Just Liberated My Modules by akie on Wednesday March 23, 2016 @05:09AM (#11343000)
No offense, but that code is much more difficult to understand. If your goal is to minimize the amount of lines, then you succeeded. If the goal is to produce both correct and readable code, then there's room for improvement.
Re:I've Just Liberated My Modules by ars on Wednesday March 23, 2016 @12:12PM (#11345742)
> No offense, but that code is much more difficult to understand.

I strongly disagree. My code has no magic initializers (the -1 in the original) and a simple linear code path, with no branching. It's very easy to read and understand.

The ternary operator at the top is simply read from left to right, it's not complicated.

> If your goal is to minimize the amount of lines, then you succeeded.

My goal was to maximize efficiency. Often that means less lines, but that was not the overt goal. And in fact this version runs faster, and uses less memory.

> If the goal is to produce both correct and readable code, then there's room for improvement.

You think so?

Then now it's your turn - rewrite this (or the original) to make it as readable as possible. I think you will find that a: mine is more readable than the original, and b: you won't be able to (need to) change much except to lift the len initializer out of the ternary operator in the first line onto its own line.

Re:I've Just Liberated My Modules by scrabble on Wednesday March 23, 2016 @11:05AM (#11345119)
If you are talking about a module that everyone just includes and expects to work, then I'd imagine the goal would be a combination of correct and efficient, not readable.