From 5a55dd13edd148718a0a0177d711b71b5887d3da Mon Sep 17 00:00:00 2001 From: jashkenas Date: Thu, 31 May 2018 12:47:37 -0700 Subject: [PATCH] Fixes #2741. _.first() and _.last() should return an empty array when requesting a specific number of elements. --- test/arrays.js | 7 +++++++ underscore.js | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/test/arrays.js b/test/arrays.js index c6e0124f5..86392ed42 100644 --- a/test/arrays.js +++ b/test/arrays.js @@ -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'); @@ -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'); diff --git a/underscore.js b/underscore.js index d19a20648..d21c32346 100644 --- a/underscore.js +++ b/underscore.js @@ -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); }; @@ -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)); };