Skip to content

Commit

Permalink
support full [].slice semantics
Browse files Browse the repository at this point in the history
  • Loading branch information
aheckmann committed Sep 29, 2012
1 parent f127c48 commit 71a864a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/sliced.js
Expand Up @@ -10,9 +10,15 @@

module.exports = function (args, slice, sliceEnd) {
var ret = [];
var start = slice || 0;

var start = slice < 0
? slice + args.length
: slice || 0;

var end = 3 === arguments.length
? sliceEnd
? sliceEnd < 0
? sliceEnd + args.length
: sliceEnd
: args.length;

for (var i = start; i < end; ++i) {
Expand Down
39 changes: 39 additions & 0 deletions test/index.js
Expand Up @@ -33,4 +33,43 @@ describe('sliced', function(){
assert.equal(o[1], r[0]);
})
})
describe('with negative start and no end', function(){
it('begins at an offset from the end and includes all following elements', function(){
var o = [3, "4", 5, null];
var r = sliced(o, -2);
assert.equal(2, r.length);
assert.equal(o[2], r[0]);
assert.equal(o[3], r[1]);
})
})
describe('with negative start and positive end', function(){
it('begins at an offset from the end and includes `end` elements', function(){
var o = [3, "4", {x:1}, null];

var r = sliced(o, -2, 1);
assert.equal(0, r.length);

var r = sliced(o, -2, 2);
assert.equal(0, r.length);

var r = sliced(o, -2, 3);
assert.equal(1, r.length);
assert.equal(o[2], r[0]);
})
})
describe('with negative start and negative end', function(){
it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){
var o = [3, "4", {x:1}, null];
var r = sliced(o, -3, -1);
assert.equal(2, r.length);
assert.equal(o[1], r[0]);
assert.equal(o[2], r[1]);

var r = sliced(o, -3, -3);
assert.equal(0, r.length);

var r = sliced(o, -3, -4);
assert.equal(0, r.length);
})
})
})

0 comments on commit 71a864a

Please sign in to comment.