Skip to content
Advertisement

How to retrieve an element from a set without removing it?

Suppose the following:

JavaScript

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it – something I can only be sure of after an asynchronous call to another host.

Quick and dirty:

JavaScript

But do you know of a better way? Ideally in constant time.

Advertisement

Answer

Two options that don’t require copying the whole set:

JavaScript

Or…

JavaScript

But in general, sets don’t support indexing or slicing.

Advertisement