Skip to content

Instantly share code, notes, and snippets.

@srph
Last active September 30, 2016 06:25
Show Gist options
  • Save srph/2da54afdb034d2ac03e21885e2e9722c to your computer and use it in GitHub Desktop.
Save srph/2da54afdb034d2ac03e21885e2e9722c to your computer and use it in GitHub Desktop.
js: slice that works from end to start (e.g., 1, 2, 3, 4, 5 -> slice(array, 3, 0) -> 4, 5, 1)
/**
* A `slice` function that works from taking
* ending positions to the starting positions
*
* @example
* slice(months, 11, 2) // ['Dec', 'Jan', 'Feb', 'Mar']
*
* @param {array} array Array to slice
* @param {start} start Starting position
* @param {end} end Ending position
* @return {array}
*/
function slice(array, start, end) {
var stack = []
var range = (end > start ? end : end + array.length) - start;
var current = start;
for ( var i = 0; i <= range; i++ ) {
stack.push(array[current]);
if ( current === array.length - 1 ) {
current = 0;
} else {
current++;
}
}
return stack;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment