Array.prototype.remove(item)

Ron Buckton Ron.Buckton at microsoft.com
Thu Oct 11 04:54:26 UTC 2018


That depends entirely on what the return value means. Returning Boolean from `add` doesn’t mean, “does the value now exist in the set”, but rather means “was the set modified as a result of this operation”.

To avoid any possible performance cost for calling `has` before `add`, I usually have to do something like:

```
function setAdd(set, value) {
  const size = set.size;
  set.add(value);
  return size !== set.size;
}
```

From: es-discuss <es-discuss-bounces at mozilla.org> On Behalf Of Jordan Harband
Sent: Wednesday, October 10, 2018 7:19 PM
To: jolleekin at outlook.com
Cc: es-discuss <es-discuss at mozilla.org>
Subject: Re: Array.prototype.remove(item)

Man: `add` doesn't need to return a boolean, because it always results in the item being in the collection after the fact. You could subclass Set, and make `.add` do that, though, if you like! Alternatively, you could use `.has` prior to calling `.add`, to get your boolean value.

On Wed, Oct 10, 2018 at 1:01 AM Man Hoang <jolleekin at outlook.com<mailto:jolleekin at outlook.com>> wrote:
The problem with `Set` is that its `add` method returns `this` instead of `boolean`. If `Set.prototype.add` returned `boolean`, I would have used `Set`.

That’s why in the `select` method of my sample code, I use a custom defined method named `pushIfAbsent`. The actual type of `_values` is not `Array` but a subclass of `Array`.
``` js
export class MyArray<E> extends Array<E> {
    /**
     * Adds [item] to the end of this array if it's not already in this array.
     *
     * Returns `true` is [item] was added, `false` otherwise.
     */
    pushIfAbsent(item: E): boolean {
        if (!this.includes(item)) {
            this.push(item);
            return true;
        }
        return false;
    }

    /**
     * Removes the first occurrence of [item] from this array.
     *
     * Returns `true` if [item] was in this array, `false` otherwise.
     */
    remove(item: E): boolean {
        const i = this.indexOf(item);
        if (i >= 0) {
            this.splice(i, 1);
            return true;
        }
        return false;
    }
}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20181011/51cb5f7e/attachment.html>


More information about the es-discuss mailing list