HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Rotating array members

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayrotatingmembers

Problem

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.

jsperf

Since I'm using this code in node.js, which uses the Chrome engine, results are important.

Solution

You should use shift and push

function rotate( array , times ){
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
}

//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );


shift removes the first element, push adds an element at the end.
I am not sure whether you are using players_new because you do not know how to modify the original array or because you do not want to modify the original. If you do not want to modify the original array you could:

function rotate( array , times ){
  array = array.slice();
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
  return array;
}

//Test
var players = ['Bob','John','Mack','Malachi'];
console.log( rotate( players ,2 ) );


Finally, if you meant to declare an array, you should have var players_new = [];, not var players_new = {};. Plus players_new is an unfortunate name.

Golfic edition:

while(times--)array.push(array.shift());

Code Snippets

function rotate( array , times ){
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
}

//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );
function rotate( array , times ){
  array = array.slice();
  while( times-- ){
    var temp = array.shift();
    array.push( temp )
  }
  return array;
}

//Test
var players = ['Bob','John','Mack','Malachi'];
console.log( rotate( players ,2 ) );
while(times--)array.push(array.shift());

Context

StackExchange Code Review Q#41006, answer score: 11

Revisions (0)

No revisions yet.