Array.prototype.toggle

manuelbarzi manuelbarzi at gmail.com
Fri Feb 7 12:23:01 UTC 2020


calling it again would just apply the same mechanism => "do this element
already exist? "remove it" : "add it". in the example, it would just add 1
at the end of array (i.e. just a push), calling it the second time.

``js
const a = [1, 2, 3, 2, 1].toggle(1) // mutates the original array removing
1 => [2, 3, 2]
a.toggle(1); // mutates the original array adding 1 => [2, 3, 2, 1]
```

On Fri, Feb 7, 2020 at 1:11 PM Scott Rudiger <scottrudiger at gmail.com> wrote:

> `Array.prototype.filter` seems more versatile (although it doesn't mutate
> the original array) since it removes elements based on a function:
>
> ```js
> [1, 2, 3, 2, 1].filter(n => n !== 1); // [2, 3, 2]
> ```
>
> Since the method is named `toggle`, what happens when you call it on the
> same array twice? Do you get the removed elements back?
>
> ```js
> const arr = [1, 2, 3, 2, 1].toggle(1) // mutates the original array
> removing 1, resulting in [2, 3, 2]
> arr.toggle(1); // ???
> ```
>
> On Fri, Feb 7, 2020 at 3:49 AM manuelbarzi <manuelbarzi at gmail.com> wrote:
>
>> just a proposal to provide this functionality into array, allowing to add
>> / remove items in a toggling mechanism shortcut, avoiding the need to do
>> traversing to locate the indexes and remove them next (i.e. by means of a
>> polyfill or any other approach).
>>
>> ```js
>> [1, 2, 3, 2, 1].toggle(1) // mutates the original array removing 1,
>> resulting in [2, 3, 2]
>> ```
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20200207/0ea181f3/attachment.html>


More information about the es-discuss mailing list