Set `.toggle` method

This would carry roughly the same kind of semantics as DOMTokenList, but also returning a boolean based on whether it previously existed for convenience and utility, something like this:

Set.prototype.toggle = function (value, include = this.has(value)) {
    if (include) {
        return this.delete(value);
    } else {
        const prev = this.size;
        this.add(value);
        return this.size !== prev;
    }
};

I've personally had as much use for it outside the DOM as in, so it'd be very useful to have. Also, engines could optimize this to always look up the value and then afterwards make the determination on whether to add or remove the value, to save a bunch on branches and code size, resulting in far less overhead.

2 Likes