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
So theThe 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.
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?
offsetThe offset
variable is probably wrongly named,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 we have a winner :) vazha's version is the fastest all around, except in firefoxFirefox.
http://jsperf.com/rotate-array-javascript
Since, I'm using this code in node.js, which uses chromethe Chrome engine, for me chrome results are important.