??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 regards,

Ron
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to