Skip to content

Instantly share code, notes, and snippets.

@RB-Lab
Created October 22, 2015 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RB-Lab/a20b50db57509e9d9818 to your computer and use it in GitHub Desktop.
Save RB-Lab/a20b50db57509e9d9818 to your computer and use it in GitHub Desktop.
/**
* function sliceRing make circular slice of array
* @param {Array} arr
* @param {Number} start
* @param {Number} length
* @returns {Array}
*/
export default function sliceRing(arr, start, length) {
start = start % arr.length;
if (start < 0) start = arr.length + start;
var end = (start + length) % arr.length;
if (start < end) {
return arr.slice(start, end);
}
return arr.slice(start).concat(arr.slice(0, end));
}
describe('Ring slice', function() {
var arr = [0, 1, 2, 3, 4, 5];
it('should slice normaly', function() {
expect(sliceRing(arr, 2, 3)).eql([2, 3, 4]);
});
it('should slice ring when start + length is bigger then length', function() {
expect(sliceRing(arr, 4, 4)).eql([4, 5, 0, 1]);
});
it('should slice when start is bigger then length', function() {
expect(sliceRing(arr, 8, 4)).eql([2, 3, 4, 5]);
});
it('should slice ring when start is bigger then length', function() {
expect(sliceRing(arr, 10, 4)).eql([4, 5, 0, 1]);
});
it('should slice ring when start is below 0', function() {
expect(sliceRing(arr, -2, 4)).eql([4, 5, 0, 1]);
});
it('should slice ring when start and further then length', function() {
expect(sliceRing(arr, -8, 4)).eql([4, 5, 0, 1]);
expect(sliceRing(arr, -14, 4)).eql([4, 5, 0, 1]);
});
it('should slice ring length is equal to array length', function() {
expect(sliceRing(arr, 2, 6)).eql([2, 3, 4, 5, 0, 1]);
expect(sliceRing(arr, -2, 6)).eql([4, 5, 0, 1, 2, 3]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment