Array swap method

for clarify and normalization the languaje, i proposed to add a built in metod for Array swap items

every developer sometime need to swap items of an existing array, and need to use something like this:

Array.prototype.swap = function(index_A, index_B)
{
let input = this;
let temp = input[index_A];
input[index_A] = input[index_B];
input[index_B] = temp;
}

I don't think I've actually ever needed to swap two items in an array. Except - maybe when implementing a bubble sort sorting algorithm back in school.

But, for the scenarios when this is needed, it's actually not too difficult to do using the destructuring syntax:

> myList = ['a', 'b', 'c', 'd', 'e']
> [myList[1], myList[3]] = [myList[3], myList[1]]
> myList
[ 'a', 'd', 'c', 'b', 'e' ]

Its about to make the language and make happy all developers, right?
why no add it? its clear, its usefull, its minimalist

Adding more mutator methods would make some developers, myself included, incredibly unhappy.

1 Like

Well, it's also about not bloating the language with lots of things that don't get used often, especially when the alternatives aren't that much worse. Every new language feature comes at the cost of adding complexity to the language. We want to keep the Javascript language as simple and approachable as possible, while still providing all of the useful tools that developers needs - it's a difficult balance.

So the question here is whether or not an added .swap() method is useful enough to warrant the added bloat it adds to the language. From my personal experience, I would say it's not worth it, because I've almost never needed such a feature, and that destructuring one-liner works good enough for the few cases I have needed it. However, I'm certainly not representative of the javascript community, and maybe others would find a swap() method more useful than I would.

I think the same as you, and I am a minimalist, however, I seek above all what is essential and clear and I think that this method complies with that

Also, engines attempt to optimize specifically for that.