From 05c107576b0bf9ce8e0bdb4433987f70e7e82aa3 Mon Sep 17 00:00:00 2001 From: David Hirtle Date: Tue, 8 Nov 2011 01:13:08 -0800 Subject: [PATCH] Fix bug with _.last(a, n) incorrectly handling n > a.length --- test/arrays.js | 2 ++ underscore.js | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/test/arrays.js b/test/arrays.js index c648f081b..ae00faf0a 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -7,6 +7,7 @@ $(document).ready(function() { 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'); + equals(_.first([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to first'); var result = (function(){ return _.first(arguments); })(4, 3, 2, 1); equals(result, 4, 'works on an arguments object.'); result = _.map([[1,2,3],[1,2,3]], _.first); @@ -37,6 +38,7 @@ $(document).ready(function() { equals(_.last([1,2,3]), 3, 'can pull out the last element of an array'); equals(_.last([1,2,3], 0).join(', '), "", 'can pass an index to last'); equals(_.last([1,2,3], 2).join(', '), '2, 3', 'can pass an index to last'); + equals(_.last([1,2,3], 5).join(', '), '1, 2, 3', 'can pass an index to last'); var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4); equals(result, 4, 'works on an arguments object'); result = _.map([[1,2,3],[1,2,3]], _.last); diff --git a/underscore.js b/underscore.js index d27970bbe..7f936f600 100644 --- a/underscore.js +++ b/underscore.js @@ -335,7 +335,7 @@ // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { - return (n != null) && !guard ? slice.call(array, array.length - n) : array[array.length - 1]; + return (n != null) && !guard ? slice.call(array, Math.max(array.length - n, 0)) : array[array.length - 1]; }; // Returns everything but the first entry of the array. Aliased as `tail`.