Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Circular Array Range
var arr = [0,1,2,3,4,5,6,7,8,9];
/**
* Returns a circular range of an Array
* @param index {Number} starting position
* @param size {Number} size of the range
* @param [position] {Number} position of the range, negative values will return a range before the index
* @return {Array}
**/
Array.prototype.range = function(index, size, position){
// make a copy
var a = this.slice(),
// if index is out of bound start counting from 0
f = index % a.length;
return (position < 0? a.splice(f - size + 1, size):a.splice(f)).concat(a).splice(0, size);
}
console.log(arr.range(9, 4)); // [9, 0, 1, 2]
console.log(arr.range(1, 4, -1)); // [8, 9, 0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.