Skip to content

Instantly share code, notes, and snippets.

@martinjoiner
Created October 13, 2016 17:01
Show Gist options
  • Select an option

  • Save martinjoiner/1395b0271a3f0271d305422f024455c4 to your computer and use it in GitHub Desktop.

Select an option

Save martinjoiner/1395b0271a3f0271d305422f024455c4 to your computer and use it in GitHub Desktop.
// rotateByN() moves a chunk of an array from the start to the end
Array.prototype.rotateByN = function(n) {
var arrReturn = [],
i,
iLimit = this.length;
// Add everything above n
for( i = n; i < iLimit; i++){
arrReturn.push( this[i] );
}
// Add everything below n
for( i = 0; i < n; i++){
arrReturn.push( this[i] );
}
return arrReturn;
};
// itemByLoopedIndex() will allow an item with an index higher than number of items to be requested
Array.prototype.itemByLoopedIndex = function(n) {
// If they are asking for a valid index item, just return it
if( n < this.length ){
return this[n];
}
var remainder = n % this.length;
return this[remainder];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment