The MDN documentation for Set says that JavaScript Set
objects retain insertion order of elements:
Set objects are collections of values, you can iterate its elements in insertion order.
Is there a way to get the last item inserted into a Set
object?
var s = new Set();
s.add("Alpha");
s.add("Zeta");
s.add("Beta");
console.log(getLastItem(s)); // prints "Beta"
Edit
It is possible to implement a Linked Set datastructure container class that has the same interface as Set
and has the desired capability. See my answer below.
prev
value in MySet, andlast()
will returnprev
in constant time. – Noelnoelani