Shu-yu Guo, Google for
Tab Atkins, Google
Relative Indexing is Kinda Nice
In Python, list[-N] returns the Nth item from the last item of the list.
Pretty ergonomic; Array#slice and Array#splice already supports relative indexing.
In JS, you can write arr[arr.length - N], but:
We Can’t Have It as Syntax
In JS,
o[1] is just o["1"],
And, alas,
o[-1] is just o["-1"].
The Proposal
function item(n) {
n = %ToInteger(n);
if(n >= 0) {
return this[n];
}
return this[this.length+n];
}
Object.defineProperty(
Array.prototype,
"item",
{ value: item,
writable: true,
enumerable: false,
configurable: true });
// Ditto for String,
// TypedArrays
Why We Should Name It .item()
A rare chance of confluence with Web APIs.
First, some background and history...
Web APIs Have Weird Bespoke Array-likes
An ObservableArray to Rule Them
WebIDL recently added ObservableArray: a Proxy of Array that lets web spec authors to trap Array MOP operations
Almost a drop-in replace weird bespoke Array-likes
Catch is: weird bespoke Array-likes all have .item(), itself a Java-ism
Compat Risk: Userland Libraries
None of them have a .item(), so cautiously optimistic
Compat Risk: Existing Web API .item()
| Web API .item(N) | Proposed JS .item(N) |
N is +Infinity or -Infinity | N = 0 | N left as-is |
N < 0 or N > 2^32 | N = N mod 2^32 | N left as-is |
N is OOB | Returns null | Returns undefined |
Compat Risk: Existing Web API .item()
| Web API .item(N) | Proposed JS .item(N) |
N is +Infinity or -Infinity | N = 0 | N left as-is |
N < 0 or N > 2^32 | N = N mod 2^32 | N left as-is |
N is OOB | Returns null | Returns undefined |
Risk assessment: very low
Compat Risk: Existing Web API .item()
| Web API .item(N) | Proposed JS .item(N) |
N is +Infinity or -Infinity | N = 0 | N left as-is |
N < 0 or N > 2^32 | N = N mod 2^32 | N left as-is |
N is OOB | Returns null | Returns undefined |
Risk assessment: slight for N < 0, very low for N > 2^32
Compat Risk: Existing Web API .item()
| Web API .item(N) | Proposed JS .item(N) |
N is +Infinity or -Infinity | N = 0 | N left as-is |
N < 0 or N > 2^32 | N = N mod 2^32 | N left as-is |
N is OOB | Returns null | Returns undefined |
Risk assessment: moderate
De-risking
Chrome is willing to gather data on existing uses of WebIDL .item()
If incompat arises,
then we bikeshed name
Stage 1?
Specifically,