Skip to content

Commit

Permalink
Merge pull request #2715 from jojois74/master
Browse files Browse the repository at this point in the history
[BUGFIX] (Bug #2714) For _.uniq which acted incorrectly on sorted lists using a non injective iteratee
  • Loading branch information
jashkenas committed Nov 27, 2017
2 parents 65e18d4 + 644cd3c commit 5c237a7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
4 changes: 4 additions & 0 deletions test/arrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@
list = [1, 1, 1, 2, 2, 3];
assert.deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster');

list = [-2, -1, 0, 1, 2];
var notInjective = function(x) {return x * x;};
assert.deepEqual(_.uniq(list, true, notInjective), [-2, -1, 0], 'can find values of sorted array which map to unique values through a non one-to-one function by switching to slower algorithm even when isSorted=true');

list = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}, {name: 'Curly'}];
var expected = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}];
var iterator = function(stooge) { return stooge.name; };
Expand Down
5 changes: 4 additions & 1 deletion underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,9 @@

// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// The faster algorithm will not work with an iteratee if the iteratee
// is not a one-to-one function, so providing an iteratee will disable
// the faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
Expand All @@ -571,7 +574,7 @@
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (isSorted && !iteratee) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
Expand Down

0 comments on commit 5c237a7

Please sign in to comment.