archives

« Bugzilla Issues Index

#4332 — Problem with string padding algorithm


The current specification for lpad/rpad at http://wiki.ecmascript.org/doku.php?id=strawman:string_padding have problems. I'm assuming the algorithm is untested.

(for this post I'm going to just be referring to lpad, but the same issues exist for rpad)

An example implementation: https://jsfiddle.net/e3ceyupt/1/

There are at least two issues with the current specification.

1) The operators for step 5 are switched:
For the lpad function to even be used, the length of the string must be less than the "minimum length". Thus, `S.length` will always be smaller than `intMinLength`, so at step 5 `fillLen = S.length - intMinLength` will always yield a value less than 0, which will then fail on step 6.

2) The specification assumes that the string for which lpad is call will always need to be padded. (That is: it assumes S.length < minLength)
A counter usage example: if I have a variable length string variable, and I want to guarantee that it's at least N characters, I should be able use `strVar.lpad(N)`. If the variable length is already >= N, then the lpad should be a no-op. Currently, the specification will throw a RangeError.
There is precedent for allowing lpad to be a no-op: python's "".ljust will return the original string in this case.

I propose the following changes be made:
- After step 4, add a step: "If intMinLength < 0, then throw a RangeError exception"
- Change step 5 to be "Let fillLen be intMinLength minus the number of characters in S"
- Change step 6 to be "if fillLen <= 0, then return S"


added champions to CC list


Seems good, thanks for the report!


Bulk closing all Harmony bugs. Proposals should be tracked on GitHub. The ES wiki is completely defunct at this point.