-
Notifications
You must be signed in to change notification settings - Fork 13
Negative indexes with array.get(-1) and array.set(-1, value) #23
Comments
It's a good idea, I think to have something like in Python where you could write |
Would That is I do like |
It could also return |
I'm not opposed to the idea, on the surface it seems good. There are two concerns with this though:
|
Yeah, I think that was the "I remember there were arguments against those methods, but forgot what they were". I think this would be very worth it, even renamed for compat issues, |
Edit: formatting What about Here's an optimized polyfill, derived from my polyfill of the current proposal here: #26 const floor = Math.floor
function computeIndex(l, n) {
l = floor(l)
n = floor(n)
if (l !== l || n !== n) return 0
if (l >= 0) {
if (l > 9007199254740991) l = 9007199254740991
if (n < 0) {
n += len
if (n <= 0) return 0
}
if (n < l) return n
}
return -1
}
function install(name, func) {
if (Object.getOwnPropertyDescriptor(Array.prototype, name) == null) {
Object.defineProperty(Array.prototype, name, {
enumerable: false,
configurable: false,
writable: true,
value: func,
})
}
}
install("index", function index(n) {
if (this == null) throw new TypeError("`this` must be coercible to an object")
return computeIndex(+this.length, +n)
})
install("at", function at(n) {
if (this == null) throw new TypeError("`this` must be coercible to an object")
const index = computeIndex(+this.length, +n)
if (index < 0) throw new RangeError("index is out of range")
return this[index]
})
install("put", function put(n, value) {
if (this == null) throw new TypeError("`this` must be coercible to an object")
const index = computeIndex(+this.length, +n)
if (index < 0) throw new RangeError("index is out of range")
this[index] = value
}) This implements the following algorithm: Abstract Operation: ResolveIndex(O, offset)
Array.prototype.index(offset)
Array.prototype.at(offset)
Array.prototype.put(offset, value)
|
.get(-1)
and.set(-1, value)
have gotten a lot of support in #5, but since it's a separate proposal (and hasn't gotten a response from @keithamus yet), I figure it probably deserves its own issue.Summary of reasons to favor it:
Map
@rauschma mentioned "I remember there were arguments against those methods, but forgot what they were", but I've yet to find any arguments against this idea.
Looking at the comments in #5, I count 17 people in support (3 comments and 14 other thumbs-ups) and no opposition.
The text was updated successfully, but these errors were encountered: