tc39 / proposal-relative-indexing-method

A TC39 proposal to add an .at() method to all the basic indexable classes (Array, String, TypedArray)
MIT License
352 stars 19 forks source link

OOB behavior #11

Closed syg closed 4 years ago

syg commented 4 years ago

For relative indices that translate to an absolute index k s.t. k < 0 or ko.length, what should the behavior be?

Some possibilities:

  1. Return undefined
  2. Return the property with name k
  3. Return the item at a clamped index, like 0 (current spec draft behavior, but this is really a bug)

I'd like to reject 3 outright, that's kinda strange.

1 seems more preferable to me, since item() is specifically for indexing, so a fallback to arbitrary property gets isn't great. I'll draft a PR that implements 1 in the draft spec.

ljharb commented 4 years ago

I agree 3 is strange, and since this is an array method to get an item, not an object method to get a property, i'd also prefer option 1.

rkirsling commented 4 years ago

s.t. k < 0

Doesn't the max() prevent this?

I was going to agree about option 1, but if we're going to call getters for non-OOB indices, I think it feels a bit weird not to give OOB indices the same opportunity...?

ljharb commented 4 years ago

I think typically Array methods (which also are expected to work on arraylikes) don't ever touch anything that's not [0, length) - this seems like it'd be the first time if we went with option 2.

rkirsling commented 4 years ago

That seems like a fair justification. I guess my inclination was to view this as "[] but as a named method".

tabatkins commented 4 years ago

I think it is a mistake to make positive and negative values act differently here. Currently, positive values just look for the property of that name, regardless of its relationship to .length (exactly like arr[x] access normally does); if we keep that as it is, then negative values should act identically, fetching the property whose name is the stringification of (length + arg) regardless of value.

Alternately, we can make both of them do bounds checks, and guarantee returning undefined when they're OOB.

I'd be happy either way, I'd just be very much against the pos/neg values being treated differently.

ljharb commented 4 years ago

I agree they shouldn't be treated differently; #12 seems to be making both of them do bounds checks, otherwise undefined, which is what makes the most sense to me for an array method.

tabatkins commented 4 years ago

Indeed, just merged it since I saw your +1 on that as well.