tc39/proposal-relative-indexing-method

How about `.get()` instead of `.at()`?

rauschma opened this issue · 9 comments

Benefits:

  • Same name as Map.prototype.get().
  • Leaves the door open for adding .set() later.

Having the same name as Map.prototype.get imo would add confusion - arrays are list-like, not strict-like, so Set, not Map, would be a better analogue - but also, Maps have keys, not indexes.

  • Arrays can have holes, which makes them more like Maps from indices to values (IMO).
  • Array.prototype.keys()
  • OTOH, having a length and a sequence-y nature (ordered elements) is indeed a distinguishing feature of Arrays, strings, and Typed Arrays.

But I find my second item more important: What would a write operation be called if the read operation is called .at()?

Sparse arrays are something that the newer parts of the spec tries very hard to pretend don’t exist :-)

A write operation could still be called “set” - there’s no requirement that both get/set or neither be present - but i also don’t think anyone’s proposed a write operation. What would one have been called when this proposal was called “item”?

  • 😀 #10
    • Another possibility: .getElement()
  • Should there ever be a .set(), people will expect a .get().
  • Precedents for read-only(!) access of a sequence data structure:
    • String.prototype.charAt()
    • String.prototype.charCodeAt

I agree with your user expectation point for sure.

I think the first thing that would have to be established is that there’s a problem that needs to be solved that would need negative indexing to assign directly to an index in an array.

I don't love introducing some FUD but I believe .get and .set methods would be eventually revealed as web incompatible. Otherwise they would be nice.

.getItem() and .getElement() are not compelling enough for me over the simple .at(), I prefer the simplicity.

I think it comes down to whether there will ever be a setter.

One way to get numbers would be to look for the following pattern in code bases:

«arr»[«arr».length - «expr»]

And then count how often the context is getting and how often setting.

hax commented

I believe .get and .set methods would be eventually revealed as web incompatible.

at could also have web compat issue. sugarjs provide Array/String.prototype.at from 10 years ago.

hax commented

«arr»[«arr».length - «expr»]

Note, another issue is , a.at(-i) actually not same as a[a.length - i] in one edge case: i === 0.

That means, if programmers refactor code a[a.length - i]?.x to a.at(-i)?.x, they may introduce a potential bug.