Remix.run Logo
wizzwizz4 3 days ago

Please don't write your own left-pad. It's built into the standard library, under the name (String.prototype.)padStart.

shermantanktop 2 days ago | parent | next [-]

That example was not picked at random.

OtomotO 2 days ago | parent | prev [-]

Exemplum docet

wizzwizz4 2 days ago | parent [-]

I have seen this argument made many times, but none of the examples used illustrated it properly. Past a certain point, one becomes suspicious of the argument itself.

chipsrafferty 2 days ago | parent [-]

Have you ever wondered why padStart is part of the standard library?

You are unaware of a core part of JavaScript history, which is why you don't understand why "I'm not importing a library to do left pad" is not only a proper example, but THE BEST example.

String.padStart was added in 2017.

This happened in 2016 https://en.m.wikipedia.org/wiki/Npm_left-pad_incident

wizzwizz4 a day ago | parent [-]

The left-pad incident was a problem with the build toolchain, not a problem with using a dependency. String padding is one of those fiddly things that you have to spend a couple of minutes on, and write 4–5 tests for, lest you get an off-by-one error. It makes perfect sense to bring in a dependency for it, if it's not available in the standard library, just as I might bring in a dependency for backprop (15 lines: https://github.com/albertwujj/genprop/blob/master/backprop.p...). My personal style is to reimplement this, but that doesn't mean it's foolish or unjustified to bring in a dependency.

It is, however, almost never justified to bring in a dependency for something that's in the standard library. The correct solution for that, in JavaScript-for-the-web, is a shim. left-pad is not a suitable example.

A better example would be https://www.npmjs.com/package/ansi-red:

  /*!
   * ansi-red <https://github.com/jonschlinkert/ansi-red>
   *
   * Copyright (c) 2015, Jon Schlinkert.
   * Licensed under the MIT License.
   */
  
  'use strict';
  
  var wrap = require('ansi-wrap');
  
  module.exports = function red(message) {
    return wrap(31, 39, message);
  };
But while this makes a point, does it really make the original point? This ansi-red library has at least two footguns, right off the bat.