When expecting a positive integer...

Domenic Denicola domenic at domenicdenicola.com
Mon Apr 8 23:05:33 PDT 2013


I notice that operations accepting positive integers do various somewhat-inconsistent things as of the latest ES6 spec:

Various typed array things do `ToPositiveInteger`, a new operation as of ES6:

  - `ArrayBuffer(length)` and `TypedArray(length)` 
  - Constructing a typed array, and `TypedArray.prototype.set`, coerce both the passed object's `length` property and the numeric byte-offset argument
  - Most interestingly, `TypedArray.prototype.@@elementGet(index)` and `@@elementSet(index, value)` do a `ToPositiveInteger` on `index`. So `typedArray[-123] === typedArray[0]`, and `typedArray[-321] = 5` gives `typedArray[0] === 5`.

Whereas arrays use `ToUint32`, but sometimes throw `RangeError`s:
  - Indices generally "work" if `ToString(ToUint32(index)) !== index`; otherwise they're treated as ordinary properties.
 - When getting a length from any array-like, you just do `ToUint32` on it.
 - But when setting a length, you validate so that if `ToUint32(length) !== length`, a `RangeError` is thrown.

Finally, one lone place throws `RangeError`s after conversion:

 - `String.prototype.repeat(count)` throws if `ToInteger(count)` is negative or infinite.

---

I was curious if there were any interesting rationales driving these decisions. (And I fully appreciate there might not be; it could just be compatibility constraints.) Or, to put it another way, I was curious what would be considered "idiomatic" JS, e.g. in the same way that the spec sets a precedent of `ToString`-ing all string inputs to its functions.


More information about the es-discuss mailing list