Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 8f236af

Browse files
committed
Update(orderBy): Guaranteed stable sort
Falls back on built-in comparison function if user-provided comparison function fails to break a tie between elements being ordered. Closes #14881
1 parent 8eb925d commit 8f236af

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/ng/filter/orderBy.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,9 @@
459459
* comparator function. For example, you might need to compare some strings in a locale-sensitive
460460
* way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
461461
* argument - passing `false` retains the default sorting order, i.e. ascending.)
462+
*
463+
* If your comparator fails to differentiate between two items, they will fall back to the built-in
464+
* comparator function, this produces a guarantee of stable sorting.
462465
*
463466
<example name="orderBy-custom-comparator" module="orderByExample4">
464467
<file name="index.html">
@@ -599,7 +602,7 @@ function orderByFilter($parse) {
599602
}
600603
}
601604

602-
return compare(v1.tieBreaker, v2.tieBreaker) * descending;
605+
return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
603606
}
604607
};
605608

test/ng/filter/orderBySpec.js

+13
Original file line numberDiff line numberDiff line change
@@ -457,6 +457,19 @@ describe('Filter: orderBy', function() {
457457

458458
expect(orderBy(items, expr, reverse, comparator)).toEqual(sorted);
459459
});
460+
461+
it('should use the default comparator to break ties on a provided comparator', function() {
462+
// Some list that won't be sorted "naturally", i.e. should sort to ['a', 'B', 'c']
463+
var items = ['c', 'a', 'B'];
464+
var expr = null;
465+
function comparator() {
466+
return 0;
467+
}
468+
var reversed = ['B', 'a', 'c'];
469+
470+
expect(orderBy(items, expr, false, comparator)).toEqual(items);
471+
expect(orderBy(items, expr, true, comparator)).toEqual(reversed);
472+
});
460473
});
461474

462475
describe('(object as `value`)', function() {

0 commit comments

Comments
 (0)