Add an optional index argument to _.last()

This makes _.last() behave the same as _.first().  Passing an optional
second argument n will return the last n elements of the array.
This commit is contained in:
Malcolm Locke
2011-08-31 22:39:05 +12:00
parent 610b347174
commit a8f0445192
2 changed files with 6 additions and 3 deletions

View File

@@ -26,6 +26,8 @@ $(document).ready(function() {
test("arrays: last", function() { test("arrays: last", function() {
equals(_.last([1,2,3]), 3, 'can pull out the last element of an array'); 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');
var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4); var result = (function(){ return _(arguments).last(); })(1, 2, 3, 4);
equals(result, 4, 'works on an arguments object'); equals(result, 4, 'works on an arguments object');
}); });

View File

@@ -306,9 +306,10 @@
return slice.call(array, (index == null) || guard ? 1 : index); return slice.call(array, (index == null) || guard ? 1 : index);
}; };
// Get the last element of an array. // Get the last element of an array. Passing **n** will return the last N
_.last = function(array) { // values in the array.
return array[array.length - 1]; _.last = function(array, n) {
return (n != null) ? slice.call(array, array.length - n) : array[array.length - 1];
}; };
// Trim out all falsy values from an array. // Trim out all falsy values from an array.