Retrieving one item from a set

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Retrieving one item from a set

medikoo
This post has NOT been accepted by the mailing list yet.
It's a while I work with sets in JavaScript (using valid polyfill in environments that do not support it yet), and already few times I approached a use case, when I was interested in single item from given set.

In some of use cases, it was about any value (but not necessary random), in others I was strictly about first or last set value. Of course sets theoretically are unordered, but are specified as deterministically ordered, and that's very useful functionality.

With current spec there's no straightforward way to retrieve one item.

Currently to get first item from set, the shortest way is:

var firstSetValue = set.values().next().value;

It's kind of dirty, as we may leave not finalized iterator, but that's probably not an issue for GC of native implementations.

Still, it's even more problematic to get last value, as then we need to iterate over whole set

var lastSetValue;
for (item of set) lastSetValue = item;

Currently I got a use case, where I save opened user payment transactions in a set, and in one place I need to refer to last one. You may say, that I may use array for that, but i totally don't need indexed collection, and arrays are too free form for that (not unique, sparse etc.). Additionally utility I use there, for very valid reason uses sets to maintain such collections.

Are there any plans to make it more convenient?