Hacker News new | comments | show | ask | jobs | submit login

Someone with more JS experience can chime in, but isn't this really inefficient in JavaScript? Wouldn't appending rather than pre-pending be better due to the way strings and memory are handled? Or at the bare minimum create the left padding in the loop and tack on str after? Can you use ch.repeat(len) + str; yet in node or if not just do the same idea of doubling in size ch until len is satisfied?

    while (++i < len) {
      str = ch + str;
And isn't this a bug?

leftpad("x", 2, '00') will return "00x"

Essentially all JS engines implement string concatenation lazily as ropes so there isn't much difference.

Well, you can do it in O(log(n)) time instead of O(n) time. But n is unlikely to be large enough for this to even matter a little bit.

Applications are open for YC Winter 2018

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact