From 7aaf3616df5734bec62886faa6909b07a5d3c931 Mon Sep 17 00:00:00 2001 From: Samuel Clay Date: Thu, 27 Jan 2011 11:38:06 -0500 Subject: [PATCH] Issue #107: Fixing issue with _.first([1,2,3], 0) returning first element instead of empty array. --- test/arrays.js | 2 ++ underscore.js | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/test/arrays.js b/test/arrays.js index 7219c038e..e031afe9b 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -5,6 +5,7 @@ $(document).ready(function() { test("arrays: first", function() { equals(_.first([1,2,3]), 1, 'can pull out the first element of an array'); equals(_([1, 2, 3]).first(), 1, 'can perform OO-style "first()"'); + equals(_.first([1,2,3], 0).join(', '), "", 'can pass an index to first'); equals(_.first([1,2,3], 2).join(', '), '1, 2', 'can pass an index to first'); var result = (function(){ return _.first(arguments); })(4, 3, 2, 1); equals(result, 4, 'works on an arguments object.'); @@ -15,6 +16,7 @@ $(document).ready(function() { test("arrays: rest", function() { var numbers = [1, 2, 3, 4]; equals(_.rest(numbers).join(", "), "2, 3, 4", 'working rest()'); + equals(_.rest(numbers, 0).join(", "), "1, 2, 3, 4", 'working rest(0)'); equals(_.rest(numbers, 2).join(', '), '3, 4', 'rest can take an index'); var result = (function(){ return _(arguments).tail(); })(1, 2, 3, 4); equals(result.join(', '), '2, 3, 4', 'aliased as tail and works on arguments object'); diff --git a/underscore.js b/underscore.js index 7c25ec41a..bd37e148b 100644 --- a/underscore.js +++ b/underscore.js @@ -284,7 +284,7 @@ // values in the array. Aliased as `head`. The **guard** check allows it to work // with `_.map`. _.first = _.head = function(array, n, guard) { - return n && !guard ? slice.call(array, 0, n) : array[0]; + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; }; // Returns everything but the first entry of the array. Aliased as `tail`. @@ -292,7 +292,7 @@ // the rest of the values in the array from that index onward. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = function(array, index, guard) { - return slice.call(array, _.isUndefined(index) || guard ? 1 : index); + return slice.call(array, (index == null) || guard ? 1 : index); }; // Get the last element of an array.