Array.prototype.remove(item)

Man Hoang jolleekin at outlook.com
Wed Oct 10 06:30:37 UTC 2018


The benefits are
- efficient (memory & speed)
- clear intent
- concise

There are always use cases where you want to mutate arrays.

How would you rewrite the following `deselect` method using `filter`?

``` js
export class Selector<T> {
    private _values: T[] = [];

    get values(): ReadonlyArray<T> {
        return this._values;
    }

    /**
     * Removes [value] from the list of selected items.
     *
     * Returns `true` if [value] was previously selected, `false` otherwise.
     */
    deselect(value: T): boolean {
        if (this._values.remove(value)) {
            this.selectionChanged([], [value]);
            return true;
        }
        return false;
    }

    /**
     * Adds [value] to the list of selected items.
     *
     * Returns `true` if [value] was not previously selected, `false` otherwise.
     */
    select(value: T): boolean {
        if (this._values.pushIfAbsent(value)) {
            this.selectionChanged([value], []);
            return true;
        }
        return false;
    }

    protected selectionChanged(addedValues, removedValues) {
        // Do something such as firing an event.
    }
}
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20181010/d8e8c421/attachment-0001.html>


More information about the es-discuss mailing list