Skip to content

Commit 5a55dd1

Browse files
committed
Fixes #2741. _.first() and _.last() should return an empty array when requesting a specific number of elements.
1 parent 3cd55ea commit 5a55dd1

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

test/arrays.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
result = _.map([[1, 2, 3], [1, 2, 3]], _.first);
1616
assert.deepEqual(result, [1, 1], 'works well with _.map');
1717
assert.strictEqual(_.first(null), void 0, 'returns undefined when called on null');
18+
assert.deepEqual(_.first([], 10), [], 'returns an empty array when called with an explicit number of elements to return');
19+
assert.deepEqual(_.first([], 1), [], 'returns an empty array when called with an explicit number of elements to return');
20+
assert.deepEqual(_.first(null, 5), [], 'returns an empty array when called with an explicit number of elements to return');
1821

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

77+
assert.deepEqual(_.last([], 10), [], 'returns an empty array when called with an explicit number of elements to return');
78+
assert.deepEqual(_.last([], 1), [], 'returns an empty array when called with an explicit number of elements to return');
79+
assert.deepEqual(_.last(null, 5), [], 'returns an empty array when called with an explicit number of elements to return');
80+
7481
var arr = [];
7582
arr[-1] = 'boo';
7683
assert.strictEqual(_.last(arr), void 0, 'return undefined when called on a empty array');

underscore.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,7 @@
497497
// values in the array. Aliased as `head` and `take`. The **guard** check
498498
// allows it to work with `_.map`.
499499
_.first = _.head = _.take = function(array, n, guard) {
500-
if (array == null || array.length < 1) return void 0;
500+
if (array == null || array.length < 1) return n == null ? void 0 : [];
501501
if (n == null || guard) return array[0];
502502
return _.initial(array, array.length - n);
503503
};
@@ -512,7 +512,7 @@
512512
// Get the last element of an array. Passing **n** will return the last N
513513
// values in the array.
514514
_.last = function(array, n, guard) {
515-
if (array == null || array.length < 1) return void 0;
515+
if (array == null || array.length < 1) return n == null ? void 0 : [];
516516
if (n == null || guard) return array[array.length - 1];
517517
return _.rest(array, Math.max(0, array.length - n));
518518
};

0 commit comments

Comments
 (0)