I had a situation when I needed to move all array elements in circular fashion. When I say this, I mean:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
The array:
var players = ["hash1","hash2","hash3","hash4"];
Players
is the array that contains user hashes and their place on the table. Table is round, so array must rotate in circular fashion.Step
dictates by how much it should move.
I came up with following algorithm (if you can call that, probably not) that works fine. I was just wondering if there was a more efficient way. Or cleaner way to do same?
The offset
variable is probably wrongly named; I couldn't come up with a better name.
var step = 0 // 3,2,1,0
var offset = 0;
var players_new = [];
for (var i = 0; i <= players.length - 1; i++) {
if (i + step <= players.length - 1) {
players_new[i + step] = players[i];
offset++;
} else {
players_new[i - offset] = players[i];
}
};
I tested many different versions, and looks like vazha's version is the fastest all around, except in Firefox.
Since I'm using this code in node.js, which uses the Chrome engine, results are important.
%
? \$\endgroup\$shift()
is the performance killer and reading the specs, shift is a generic method that reads properties of the array to determine how to shift it. So in a all rounder way shift is easy but your solution only works for your use case. It is impressive performance increase in your case :) I hope your Array contains millions of players :) \$\endgroup\$