Skip to content

Instantly share code, notes, and snippets.

@Manoj85
Forked from MarcelloDiSimone/circular_range.js
Last active August 29, 2015 14:16
Show Gist options
  • Save Manoj85/bfbc3ae14023b3afa1ef to your computer and use it in GitHub Desktop.
Save Manoj85/bfbc3ae14023b3afa1ef to your computer and use it in GitHub Desktop.
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