Skip to content

Commit

Permalink
Merge pull request #169 from mout/issue-168
Browse files Browse the repository at this point in the history
Fix negative start/end values for array/slice
  • Loading branch information
millermedeiros committed Feb 4, 2014
2 parents bbc4d4e + b5c4b1e commit cd0bf1e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
5 changes: 4 additions & 1 deletion doc/array.md
Original file line number Diff line number Diff line change
Expand Up @@ -670,7 +670,8 @@ Returns a new array containing the items from `arr` from the start index to the
end index.

If `start` is omitted, it will start at `0`. If `end` is omitted, it will used
the last index of the array.
the last index of the array. If `start` or `end` is negative, it is used as an
offset from the end of the array.

It will also convert array-like objects to arrays.

Expand All @@ -681,6 +682,8 @@ slice([1, 2, 3, 4], 1, 2); // [2, 3]
slice([1, 2, 3], 1); // [2, 3]
slice([1, 2, 3]); // [1, 2, 3]
slice({ length: 2, 0: 'a', 1: 'b' }); // ['a', 'b']
slice([1, 2, 3], 0, -1); // [1, 2]
slice([1, 2, 3], -2); // [2, 3]
```


Expand Down
7 changes: 5 additions & 2 deletions src/array/slice.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
define(function () {

var arrSlice = Array.prototype.slice;

/**
* Create slice of source array or array-like object
*/
function slice(arr, start, end){
if (start == null) {
start = 0;
} else if (start < 0) {
start = Math.max(arr.length + start, 0);
}

if (end == null) {
end = arr.length;
} else if (end < 0) {
end = Math.max(arr.length + end, 0);
}

var result = [];
Expand Down
13 changes: 13 additions & 0 deletions tests/spec/array/spec-slice.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ define(['mout/array/slice'], function(slice){
expect( result ).not.toBe( arr );
});

it('should accept negative start and end', function() {
var arr = [1, 2, 3, 4];
expect( slice(arr, 0, -2) ).toEqual( [1, 2] );
expect( slice(arr, -2, 4) ).toEqual( [3, 4] );
expect( slice(arr, -2, -1) ).toEqual( [3] );
});

it('should not allow negative start/end beyond array length', function() {
var arr = [1, 2, 3];
expect( slice(arr, -5, 2) ).toEqual( [1, 2] );
expect( slice(arr, 0, -5) ).toEqual( [] );
});

it('should convert array-like object to array', function(){
var obj = { 'length': 3, 0: 'a', 1: 'b', 2: 'c' },
result = slice(obj);
Expand Down

0 comments on commit cd0bf1e

Please sign in to comment.