Array.prototype.remove(item)

Claude Pache claude.pache at gmail.com
Wed Oct 10 07:43:39 UTC 2018


For that specific example, I think that a Set is more appropriate:

``` js
export class Selector<T> {
    private _set = new Set;
 
    get values(): ReadonlyArray<T> {
        return Array.from(this._set);
        // although it might be better to return an iterator: return this._set.values();
    }

    deselect(value: T): boolean {
        if (this._set.delete(value)) {
            this.selectionChanged([], [value]);
            return true;
        }
        return false;
    }

    // etc.
}
```

More generally, each time you are tempted to use an add()/remove()/toggle()/contains()/etc() method on an Array, you should ask yourself if it would not be better (more efficient, clearer intent, more concise, ...) to use a Set instead.

—Claude


> Le 10 oct. 2018 à 08:30, Man Hoang <jolleekin at outlook.com> a écrit :
> 
> 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.
>     }
> }
> ```
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org <mailto:es-discuss at mozilla.org>
> https://mail.mozilla.org/listinfo/es-discuss <https://mail.mozilla.org/listinfo/es-discuss>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20181010/406244cc/attachment-0001.html>


More information about the es-discuss mailing list