Get last value inserted into a Set
I was not able to find any method to get last value inserted in set from ECMA 2015 Specification, may be they never intended such a method, but you can do something like:
const a = new Set([1, 2, 3]);
a.add(10);
const lastValue = Array.from(a).pop();
Edit:
on second thought, a space efficient solution might be:
function getLastValue(set){
let value;
for(value of set);
return value;
}
const a = new Set([1, 2, 3]);
a.add(10);
console.log('last value: ', getLastValue(a));
Some ideas:
Consider using an array instead of a set. Extracting the last element of an array is easy, e.g.
array[array.length-1]; array.slice(-1)[0]; array.pop(); // <-- This alters the array
If you really need a set, you can convert it to an array when you want to extract the last item, but that will cost time and space.
Iterate the set manually. This will cost time but not as much space as copying into an array. For example (there are probably more elegant ways to do this)
var set = new Set([1, 2, 3]); var iter = set.values(), prev, curr; do { prev = curr; curr = iter.next(); } while(!curr.done) var last = prev.value; // 3
Consider inserting the items in reverse order. Then you only need to get the first item in the set, and that's easier:
set.values().next().value;
Subclass
Set
to add this new functionality:class MySet extends Set { add(value) { super.add(value); this.last = value; } } var set = new MySet(); set.add(1); set.add(2); set.add(3); set.last; // 3
Note this will only detect values added with
add
. To be more complete, it should also detect the latest value when the set is constructed, and update the value when the last item is removed.