Open syg opened 6 years ago
+1. Specially because it rules out peek() in your list of considered alternatives.
I would be interested in gathering use cases for setting also. I'm personally happy with just the getter. Perhaps @domenic who spoke about a getter/setter combo in the January 2018 meeting could provide some insight?
Basically all the reasons listed in the readme for the getter also apply to the setter. So they seem like a package deal to me; they are about as useful as each other.
@domenic Maybe just my failure of imagination here, I rarely need to set the last item, but often need to get it. Some links to some existing code would be appreciated.
Intuitively I agree with you @domenic but when pushed by @syg to come up with a concrete use case I struggle.
Can we replace the setter with a followup proposal for a more generic setters for any position?
let arr = [1, 2, 3];
arr.setIndex(arr.lastIndex, 4);
arr === [1, 2, 4];
@jamiebuilds What you just proposed for setIndex
is basically splice
with a fixed deleteCount
of 1
.
Array.prototype.setIndex = function(i, obj) { this.splice(i, 1, obj) }
I'm not sure that it is valuable to save 2 keystrokes for 1,
in this scenario.
Although now that I think about it, you save 0 keystrokes because setIndex
is 2 longer than splice
😄
Does arr[arr.lastIndex] = 4
not suffice?
I've just grepped all the projects I'm involved with. Brace-expansion popped up in several and includes:
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
I found another instance of modifying the final string in an array and a couple of instances where the final dictionary object was replaced wholesale. But, out of thousands of references to the last element, those were the only five times lastItem
was assigned to. YMMV.
I'm interested in the compelling use cases.