4 ms·
Keep in mind that `String.prototype.repeat` exists in far fewer contexts than a simple loop. The whole point of using a module is that you don't have to worry a
by skeoh 11y ago
Keep in mind that `String.prototype.repeat` exists in far fewer contexts than a simple loop. The whole point of using a module is that you don't have to worry about _how_ it works when implementing it in your project.
- minitech 11y agoThat’s also the whole point of using a function. (For what it’s worth, I changed it from this to show off ES6.) function repeat(s, times) { return new Array(times + 1).join(s); } function padLeft(s, width, padCharacter) { var d = width - s.length; return d <= 0 ? s : repeat(padCharacter || " ", d) + s; }
- skeoh 11y agoSure. And it's easy to copy and paste into a few different projects that you maintain. What happens, however, when you decide to use multiple characters instead of a single character (to create a pattern for example)? Now your padding is two or more times as long as needed. So you write a little extra logic but now you have to update multiple projects to implement that same change. I think what's great about external modules is: * you only need to update the package file to get the benefits of new versions of dependencies * you can call `require('left-pad')` instead of what can end up like `require('../../utils/string').leftPad` * your code only describes _what_ it's doing, not _how_ (declarative programming)
- minitech 11y ago> What happens, however, when you decide to use multiple characters instead of a single character (to create a pattern for example)? Then you can’t use left-pad, because it doesn’t support that and you don’t maintain it. So you make your own module to suit your needs, which is a very good thing and returns somewhat to the actual point, which is that anyone can make their own left-pad that matches the existing module, so the author’s wishes wouldn’t have a huge impact even if they were that the module stayed down, which they weren’t. Phew!