2
\$\begingroup\$

I discovered that the JavaScript sets are ordered but don't offer a method to take the first element out of the set. For the arrays this operation exists and it's called shift.

A very basic implementation can be written in this way:

function shiftSet(s) {
    let res;
    for (let v of s) {
        res= v;
        break;
    }
    s.delete(res);
    return res;
}

Do you see a better way to write it?

\$\endgroup\$
3
\$\begingroup\$

The first element of a set can be retrieved by calling the next() method on an iterator of the Set object. Since you’re using a for...of statement, such an iterator is already used under the hood (the same is true for forEach and the spread operator).

Apart from that, there is no reason to shorten the variable names like you did. Generally, it makes code less readable. Call it set, not s.

Your function can be rewritten like this:

function shiftSet(set) {
    const firstValue = set.values().next().value;
    set.delete(firstValue);
    return firstValue;
}
\$\endgroup\$
  • \$\begingroup\$ @Blindman67 This is not the case. values() creates a new iterator, not a new array. Also, in your solution, [Symbol.iterator]() will return the same iterator. Our solutions are virtually the same and where posted at the same time. :) \$\endgroup\$ – kleinfreund Feb 17 '18 at 21:07
  • \$\begingroup\$ Yes just realized that \$\endgroup\$ – Blindman67 Feb 17 '18 at 21:08
3
\$\begingroup\$

Another way to do it is via the iterator function.

function shifySet(set) {
    const first = set[Symbol.iterator]().next().value;
    set.delete(first);
    return first;
}

I was going to check if there was an item, but it seams pointless. Works the same as your function shifts the first entry, returning it, or undefined if not found.

I would make a slight change to your version

function shiftSet(set) {
    for (const res of set) {
        set.delete(res);
        return res
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.