-
-
Save Manoj85/bfbc3ae14023b3afa1ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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