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 <[email protected]> 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
> [email protected] <mailto:[email protected]>
> https://mail.mozilla.org/listinfo/es-discuss
> <https://mail.mozilla.org/listinfo/es-discuss>
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss