Skip to content

Instantly share code, notes, and snippets.

@MarcelloDiSimone
Last active May 8, 2022 21:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarcelloDiSimone/0fab960a1d3e5db9184c to your computer and use it in GitHub Desktop.
Save MarcelloDiSimone/0fab960a1d3e5db9184c to your computer and use it in GitHub Desktop.
Circular Array Range
function ExtendedArray() {
let arr = [];
arr.push.apply(arr, arguments);
/**
* Returns a circulating range of an Array
* @param index {Number} starting position
* @param size {Number} size of the range
* @param [reverse] {Boolean} reverse the range lookup
* @return {Array} The returned array length will not exceed the length of the original array if size > arr.length
**/
arr.circularRange = function(index, size, reverse){
// make a copy
let a = this.slice(),
// if index is out of bound start counting from 0
f = index % a.length;
return (reverse === true? a.splice(f - size + 1, size):a.splice(f)).concat(a).splice(0, size);
}
return arr;
}
var arr = ExtendedArray(0,1,2,3,4,5,6,7,8,9);
console.log(arr.circularRange(9, 4)); // [9, 0, 1, 2]
console.log(arr.circularRange(1, 4, true)); // [8, 9, 0, 1]
console.log(arr.circularRange(9, 12)); // when size excedes length: [9, 0, 1, 2, 3, 4, 5, 6, 7, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment