tc39 / proposal-array-last

A JavaScript TC39 Proposal for getting the last element from an array
311 stars 13 forks source link

What are the use cases for being able to set the last item? #16

Open syg opened 6 years ago

syg commented 6 years ago

I'm interested in the compelling use cases.

samuelgoto commented 6 years ago

+1. Specially because it rules out peek() in your list of considered alternatives.

keithamus commented 6 years ago

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?

domenic commented 6 years ago

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.

syg commented 6 years ago

@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.

keithamus commented 6 years ago

Intuitively I agree with you @domenic but when pushed by @syg to come up with a concrete use case I struggle.

jamiebuilds commented 6 years ago

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];
styfle commented 6 years ago

@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 😄

keithamus commented 6 years ago

Does arr[arr.lastIndex] = 4 not suffice?

fuchsia commented 6 years ago

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.