It's even worse than it appears.
Sunday June 7, 2020; 10:05 AM EDT
  • I just wrote a JavaScript function that pads a string with a character you supply, to a certain number of places. You call it like this:#
    • pad (8, "0", 4)#
  • It would return:#
    • 0008#
  • It's a useful thing to have around.#
  • Now how would you write it?#
  • I bet you could do it in a single expression. It might be hard to understand, but in a way that's kind of cool. You have to be smart to understand it. #
  • However, as a less spectacular coder, I would write it in eight lines of the most boring code possible. For example, #
    • function pad (val, withchar, ctplaces) {#
      • var s = val.toString ();#
      • while (s.length < ctplaces) {#
        • s = withchar + s;#
        • }#
      • return (s);#
      • }#
  • I can quickly read it and see what it does. I don't have to spend any time thinking about it, so I get on with my project that much more quickly.#
  • Now this might strike you as inefficient. Look at all that code, and the looping. Oy. For fun, write a benchmark script. Call it a million times and see how long it takes. I'm pretty sure you'll see that it's fast enough. #
  • PS: It tooks 0.04 seconds to call pad (8, "0", 4) a million times on my iMac. Here's a screen shot of the code.#
  • PPS: Albert Einstein said "Everything should be made as simple as possible, but not simpler." #

© 1994-2020 Dave Winer.

Last update: Monday June 8, 2020; 10:14 AM EDT.

You know those obnoxious sites that pop up dialogs when they think you're about to leave, asking you to subscribe to their email newsletter? Well that won't do for Scripting News readers who are a discerning lot, very loyal, but that wouldn't last long if I did rude stuff like that. So here I am at the bottom of the page quietly encouraging you to sign up for the nightly email. It's got everything from the previous day on Scripting, plus the contents of the linkblog and who knows what else we'll get in there. People really love it. I wish I had done it sooner. And every email has an unsub link so if you want to get out, you can, easily -- no questions asked, and no follow-ups. Go ahead and do it, you won't be sorry! :-)