Array.prototype.toggle

manuelbarzi manuelbarzi at gmail.com
Sat Feb 8 12:45:08 UTC 2020


no intention in this proposal to discuss the `how`, but just the `what`, as
i assume everybody here knows how to implement it in a polyfill, single
function or any other approach. the proposal just goes on the idea that
"hey, we have already semantic things like `some`, `every`, etc... in
array, wouldn't it be useful to have the `toggle` too? which in my case i
found using and reusing in various projects already. how about you, guys?"
then if there is enough quorum, just thinking about integrating it or not.
that's all. thank you.

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

> I believe this wouldn't result in the OP's desired results since the
> filtered array is no longer the same length as the original array:
>
> ```js
> var toggle = (arr, el) => Object.assign(arr, arr.filter(n => n !== el));
>
> toggle([1, 2, 3, 2, 1], 1); // [2, 3 ,2, 2, 1]
> ```
>
> Here's a helper function that would work (and also push the element if
> it's not included in the original array):
>
> ```js
> var toggle = (arr, el) => {
> var len = arr.length;
>
> for (var i = 0; i < arr.length; i++)
> if (arr[i] === el)
> arr.splice(i--, 1);
>
> if (arr.length === len)
> arr.push(el);
>
> return arr;
> };
>
> var a = toggle([1, 2, 3, 2, 1], 1); // mutates the original array
> removing 1 => [2, 3, 2]
> toggle(a, 1); // mutates the original array adding 1 => [2, 3, 2, 1]
> ```
>
>
> On Fri, Feb 7, 2020 at 11:26 AM Herby Vojčík <herby at mailbox.sk> wrote:
>
>> On 7. 2. 2020 13:11, Scott Rudiger 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]
>> > ```
>>
>> But what if one wants to mutate in-place. Would this work?
>>
>>    Object.assign(arr, arr.filter(n => n !== 1))
>>
>> If not, maybe there can be
>>
>>    aCollection.replaceWith(anIterable)
>>
>> Herby
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20200208/cc705a5d/attachment.html>


More information about the es-discuss mailing list