means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
Array.prototype.swap = function (x,y) {
var b = this[x];
this[x] = this[y];
this[y] = b;
return this;
}
which can be called like:
list.swap( x, y )
This is a clean approach to both avoiding memory leaks and DRY.
You can swap any number of objects or literals, even of different types, using a simple identity function like this:
var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);
For your problem:
var swap = function (x){return x};
list[y] = swap(list[x], list[x]=list[y]);
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.
This seems ok....
Howerver using
means a b variable is going to be to be present for the rest of the scope. This can potentially lead to a memory leak. Unlikely, but still better to avoid.
Maybe a good idea to put this into Array.prototype.swap
which can be called like:
This is a clean approach to both avoiding memory leaks and DRY.
Well, you don't need to buffer both values - only one:
There is one interesting way of swapping:
(ES6 way)
Swap the first and last element in an array without temporary variable or ES6 swap method [a, b] = [b, a]
[a.pop(), ...a.slice(1), a.shift()]
Usage:
You can swap any number of objects or literals, even of different types, using a simple identity function like this:
For your problem:
This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments
a=b
etc, happen aftera
is passed into the function.