var array:Array = ['a', 'b', 'c', 'd', 'e', 'f'];
for (var offset:int = -3; offset < 4; offset++) {
print_offset(array, offset);
}
function print_offset(arr:Array, offset:int):void {
for (var i:int = 0; i < arr.length; i++) {
var index:int = (((offset + i) % arr.length) + arr.length) % arr.length;
trace(arr[index]);
}
trace("---");
}
Outputs the following:
d
e
f
a
b
c
---
e
f
a
b
c
d
---
f
a
b
c
d
e
---
a
b
c
d
e
f
---
b
c
d
e
f
a
---
c
d
e
f
a
b
---
d
e
f
a
b
c
---
You should change the offset function into something more suitable to your use case where you pass center and count and it gives just part of the array.
The modulus operator allows an index to wrap around some number.
An example:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
...
It gets tricky with negative numbers:
-1 % 3 = -1
What I usually do in this case is:
(i + 3) % i
but only if I know absoluteValue(i) < length.
If I have absolutely no guarantee about the index the right thing to do would be:
((index % length) + length) % length
The inner most operation gives a value between -length and +length
The second operation applied gives a value between 0 and 2 * length
The last operation limits it to 0 and length which is what we want.