Skip to content

Commit 5c237a7

Browse files
authored
Merge pull request #2715 from jojois74/master
[BUGFIX] (Bug #2714) For _.uniq which acted incorrectly on sorted lists using a non injective iteratee
2 parents 65e18d4 + 644cd3c commit 5c237a7

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

test/arrays.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,10 @@
154154
list = [1, 1, 1, 2, 2, 3];
155155
assert.deepEqual(_.uniq(list, true), [1, 2, 3], 'can find the unique values of a sorted array faster');
156156

157+
list = [-2, -1, 0, 1, 2];
158+
var notInjective = function(x) {return x * x;};
159+
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');
160+
157161
list = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}, {name: 'Curly'}];
158162
var expected = [{name: 'Moe'}, {name: 'Curly'}, {name: 'Larry'}];
159163
var iterator = function(stooge) { return stooge.name; };

underscore.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,9 @@
558558

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

0 commit comments

Comments
 (0)