3 ms·
Your version is quite inefficient too... If you call `insert(_:atIndex:)` N times it will obviously move the entire content of the string N times by only a sing
by lhecker 11y ago
Your version is quite inefficient too... If you call `insert(_:atIndex:)` N times it will obviously move the entire content of the string N times by only a single character.
The optimal solution would be instead if you create a `CollectionType` which repeats the padding character N times. That way you could use `insertContentsOf(_:at:)` to insert N characters at once into the string and move the contents of the string only once.
If that doesn't work for you might as well simply allocate a new `String`, reserve `pad` chars of space, insert the `pad` chars and then insert the previous string. Even that is probably still faster than your previous approach.
In the end it's still probably the easiest approach in practice to simply use the `NSString` method `stringByPaddingToLength(_:withString:startingAtIndex:)`... :D
- kennywinker 11y agoThanks for the code review. To me this is the ultimate irony of this whole thing. Many have read it as "you should have written your own leftpad function, it's 11 lines!!" But no bit of code is too short to be buggy / inefficient. Centralizing it allows us to optimize/fix once. While my implementation is basically a direct port of node's leftpad, pull requests are welcome. :)