Permalink
Browse files

support full [].slice semantics

  • Loading branch information...
1 parent f127c48 commit 71a864ac64edf0e743e9745eb4c6a14532ce4c99 @aheckmann committed Sep 29, 2012
Showing with 47 additions and 2 deletions.
  1. +8 −2 lib/sliced.js
  2. +39 −0 test/index.js
View
@@ -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) {
View
@@ -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.