Eduardo Arruda Pimentel Eduardo Arruda Pimentel - 7 months ago 24
Javascript Question

How can I loop an array from certain position in clockwise and counterclockwise?

I have this array:

var array = [0,1,2,3,4,5,6,7,8,9,10];


To Loop in a Clockwise Direction ( Start 8, then 9, then 10, then 0.....) I'm doing this way:

var start = 8;
for(i = 0; i < array.length; i++){
index = (start+i)%array.length;
....
}


1) To Clockwise Direction, there's a better way?

2) To Loop in a CounterClockwise Direction (Start 2, then 1, then 0, then 10...), what should I do?

Answer

To do it similar to what you did, decrease the index from the starting index and add the length before trimming:

var start = 8;
for(i = 0; i < array.length; i++) {
  index = (start - i + array.length) % array.length;
  // ....
}

Regarding "how to do it better", I'd create a simple helper function:

function getIndexInRange(index, length) {
  var trim = index % length;
  var nonNegative = trim + length;
  return nonNegative % length;
}

Then it all becomes clearer:

var start = 8;
for(i = 0; i < array.length; i++) {
  var index = getIndexInRange(start + i, array.length);
  // ....
}

for(i = 0; i < array.length; i++) {
  var index = getIndexInRange(start - i, array.length);
  // ....
}

Now you can even iterate the array multiple times if you want, and it still works:

for(i = 0; i < array.length * 5; i++) {
  var index = getIndexInRange(start - i, array.length);
  // ....
}