Skip to content

Commit

Permalink
Fixes #2741. _.first() and _.last() should return an empty array when…
Browse files Browse the repository at this point in the history
… requesting a specific number of elements.
  • Loading branch information
jashkenas committed May 31, 2018
1 parent 3cd55ea commit 5a55dd1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 7 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
result = _.map([[1, 2, 3], [1, 2, 3]], _.first);
assert.deepEqual(result, [1, 1], 'works well with _.map');
assert.strictEqual(_.first(null), void 0, 'returns undefined when called on null');
assert.deepEqual(_.first([], 10), [], 'returns an empty array when called with an explicit number of elements to return');
assert.deepEqual(_.first([], 1), [], 'returns an empty array when called with an explicit number of elements to return');
assert.deepEqual(_.first(null, 5), [], 'returns an empty array when called with an explicit number of elements to return');

Array.prototype[0] = 'boo';
assert.strictEqual(_.first([]), void 0, 'return undefined when called on a empty array');
Expand Down Expand Up @@ -71,6 +74,10 @@
assert.deepEqual(result, [3, 3], 'works well with _.map');
assert.strictEqual(_.last(null), void 0, 'returns undefined when called on null');

assert.deepEqual(_.last([], 10), [], 'returns an empty array when called with an explicit number of elements to return');
assert.deepEqual(_.last([], 1), [], 'returns an empty array when called with an explicit number of elements to return');
assert.deepEqual(_.last(null, 5), [], 'returns an empty array when called with an explicit number of elements to return');

var arr = [];
arr[-1] = 'boo';
assert.strictEqual(_.last(arr), void 0, 'return undefined when called on a empty array');
Expand Down
4 changes: 2 additions & 2 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null || array.length < 1) return void 0;
if (array == null || array.length < 1) return n == null ? void 0 : [];
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
Expand All @@ -512,7 +512,7 @@
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null || array.length < 1) return void 0;
if (array == null || array.length < 1) return n == null ? void 0 : [];
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
Expand Down

0 comments on commit 5a55dd1

Please sign in to comment.