Static typing would actually fix this kind of coding error.
> Static typing would actually fix this kind of coding error.
That's not a coding error, that's addressing an oddity of JS coercion rules that a less experienced developer could easily have missed.
> if (!ch && ch !== 0) ch = ' '
That code says that if `ch` is falsey and not equal to 0, then set it to a space. The only arguable falsey value that should be excluded here is a literal `false`, but that's not a single character and is fairly ambiguous either way. I'd certainly fall on the side that a literal false should not be converted to `'false'` here.
> ch += '';
The next line converts to to a string by adding it to the empty string.
> return ch.repeat(len) + str;
So by the time it gets to this line we know ch is a string.
Static typing is great, but the bug you claim is there is not actually there.
It may specialize or inline, but that's a separate matter.
P.S. I think there's a bug here.
Step 1, inline repeat.
Step 2, remove the intermediate array allocation
Step 3, allocated a string array sized for the pad + str
Step 4, Use one of the many CPU instructions to repeatably copy the padding character and then the `str` into the same array of characters.
None of these optimization would be out of the question for the Jit (and I'd expect them). You don't need the cache at all, it's just a waste. The only thing it saves it creating the intermediate string which is HIGHLY likely to be optimized away with the simple code.Nowadays there's a native padStart function and the left-pad package is deprecated as a result.
JITs only optimize hot code which means any benchmark without a warmup is going to measure cold + hot code time.
Further, JITs will optimize away unused results. They aren't using the leftpad results in any meaningful way.
What they are likely measuring is how long it takes for the JIT to optimize the benchmarking framework.
watch: https://vimeo.com/78900556 for how to microbenchmark a JITed language.
Luckily, they didn't, and instead pulled in the the `benchmark` library as a development dependency[1]. The author of said library works on V8, and already considered all those problems and much, much, more[2].
[1]: https://github.com/left-pad/left-pad/blob/master/perf/perf.j...
Sure, It's popular. It's also wrong.
I've not profiled it, but I'm going to guess that now-a-days this will be faster than the current implementation on npm.
Why? because the VM is (very likely) going to do exactly what the cache would have done. It can replace `ch.repeat(len) + str;` with a presized string allocation and a memcpy of ch + str characters.