← Back to context

Comment by jodrellblank

2 hours ago

leftpad was a focused custom implementation of a specific feature, instead of a library full of generalized functionality. At the time it was pulled, the leftpad code (JavaScript, Node, NPM) was:

    module.exports = leftpad;
    
    function leftpad (str, len, ch) {
      str = String(str);
    
      var i = -1;
    
      ch || (ch = ' ');
      len = len - str.length;
    
    
      while (++i < len) {
        str = ch + str;
      }
    
      return str;
    }

A newer version was: https://github.com/left-pad/left-pad/blob/master/index.js which cached common cases and improved on the loop performance, before String.prototype.padStart() became a thing https://www.npmjs.com/package/string.prototype.padstart

Both old and new versions return a string longer than `len` if the padding char is multiple characters, e.g. leftpad('a', 3, '&&&&') will be longer than 3. That feels like it shouldn't happen.

That's almost the first literal exercise with strings you'll learn with "The C prog lang 2nd ed" ebook. One of the most trivial cases among writting a word/space/tabs counting program (wc under Unix).

I realize I may have made it seem like I was saying leftpad was a general-purpose library. My aside about it was to note that even widely used libraries can still have bugs. That’s orthogonal to their scope.