Reputation: 1892
can anyone suggest a snippet or a short method to solve this:
array = [a,b,c,d,e,f]
currentIndex = 2;
getOffset(array,currentIndex,2); // 2+2 = 4 -> return 'e'
getOffset(array,currentIndex,-2); // -> return 'a'
getOffset(array,currentIndex,-3); // -> return 'f'
getOffset(array,currentIndex,-4); // -> return 'e'
getOffset(array,currentIndex, 5); // -> return 'b'
So if the the targetted index is bigger than array.length or < 0 -> simulate a circle loop inside the array and continue to step inside the indexes.
Can anyone help me? I tried, but got a buggy script :(
TY!
Upvotes: 2
Views: 5745
Reputation: 122916
This should do the trick, I suppose:
function getOffset(arr,n,offset) {
offset = offset || 0;
var raw = (offset+n)%arr.length;
return raw < 0 ? arr[arr.length-Math.abs(raw)] : arr[raw];
}
var arr = ["a", "b", "c", "d", "e", "f"];
getOffset(arr,-3,2); //=> 'f'
getOffset(arr,-3); //=> 'd'
//but also ;~)
getOffset(arr,-56,2); //=> 'a'
getOffset(arr,1024,2); //=> 'a'
Upvotes: 2
Reputation: 1535
Use the modulus operator:
function getOffset(arr, index, step) {
return arr[(((index + step) % arr.length) + arr.length) % arr.length];
}
Upvotes: 0
Reputation: 40448
Try this:
function getOffset(arr,index, offset){
return arr[(arr.length+index+(offset%arr.length))%arr.length];
}
Upvotes: 5