/** * Pretend the array is a circle and grab a new array containing length elements. * If length is not given return the element at start, again assuming the array * is a circle. * * @param {Number} start The index to start wrapping at, or the index of the * sole element to return if no length is given. * @param {Number} [length] Optional length determines how long result * array should be. * @returns The element at start mod array.length, or an array of length elements, * starting from start and wrapping. * @type Object or Array */ Array.prototype.wrap = function(start, length) { if(length != null) { var end = start + length; var result = []; for(var i = start; i < end; i++) { result.push(this[i.mod(this.length)]); } return result; } else { return this[start.mod(this.length)]; } };
Simple use:
[1, 2, 3].wrap(-1) => 3
[1, 2, 3].wrap(6) => 1
Or get fancy and tile your kitchen:
["w", "o", "o", "o"].wrap(0, 16) => ["w", "o", "o", "o", "w", "o", "o", "o", "w", "o", "o", "o", "w", "o", "o", "o"]