Should `Set.prototype.add` return boolean instead of `this`?

# Ron Buckton (11 years ago)

??I recall from earlier discussions on this list that the reason Set.prototype.add returns this is to support chained calls to the set, to add multiple items, similar to how some libraries like jQuery operate, for example:


var s = new Set();

s.add(1).add(2).add(3);

I have found myself using Set more and more and have found that there are more instances where I would rather it return a boolean value, where true means the value was added to the set, and false when the value was not added as it already exists. Without this, I only have two options to detect whether an item was added to the set: (a) test using Set.prototype.has before adding the value, or (b) test using Set.prototype.size after adding the value.

(a) Test using Set.prototype.has


var s = new Set();

...

if (!s.has(value)) {

  s.add(value);
  // code that executes only for unique values...

}

The problem with this solution is that we have to look up the value in the Set instance twice. As the Set grows, the cost of this algorithm will always be double the cost of the lookup. I imagine implementations can (and likely will) attempt to cache recent lookups for performance to mitigate this cost, however to a consumer of Set it could appear as if I'm still performing the same lookup twice.

(b) Test using Set.prototype.size


var s = new Set();

...

var size = s.size;

s.add(value);

if (size < s.size) {
  // code that executes only for unique values...

}

This solution removes the double lookup, but feels unnecessarily wordy and unintuitive.

Proposal: Set.prototype.add returns Boolean


var s = new Set();

...

if (s.add(value)) {

  // code that executes only for unique values
}

This seems the most concise and intuitive, and mirrors the Set.prototype.delete method's return behavior. From the consumer's perspective it has the appearance that the lookup only needs to be performed once.

Best ,

Ron

# Erik Arvidsson (11 years ago)

Seems reasonable but it is too late to make any changes to ES6.

# Allen Wirfs-Brock (11 years ago)

On Oct 16, 2014, at 11:27 AM, Erik Arvidsson wrote:

Seems reasonable but it is too late to make any changes to ES6.

I agree, but it's possible to propose extending Set,prototype with additional methods.

For example an 'addB' method that is similar to 'add' but returns a Boolean result.

Feel free to bikeshed...

# Mark S. Miller (11 years ago)

Ok. No matter what the name, adding another method only to make this distinction is not worth it. I'm against it. KIS.