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

Commit

Permalink
feat(orderBy): Stable sort the input
Browse files Browse the repository at this point in the history
Stable sort the input array

Closes #12408
Fixes #12405
  • Loading branch information
lgalfaso committed Aug 8, 2015
1 parent a268c29 commit ed3a33a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ng/filter/orderBy.js
Expand Up @@ -183,6 +183,10 @@ function orderByFilter($parse) {
if (sortPredicate.length === 0) { sortPredicate = ['+']; }

var predicates = processPredicates(sortPredicate, reverseOrder);
// Add a predicate at the end that evaluates to the element index. This makes the
// sort stable as it works as a tie-breaker when all the input predicates cannot
// distinguish between two elements.
predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});

// The next three lines are a version of a Swartzian Transform idiom from Perl
// (sometimes called the Decorate-Sort-Undecorate idiom)
Expand Down
29 changes: 29 additions & 0 deletions test/ng/filter/orderBySpec.js
Expand Up @@ -194,6 +194,35 @@ describe('Filter: orderBy', function() {
it('should sort mixed array of objects and values in a stable way', function() {
expect(orderBy([{foo: 2}, {foo: {}}, {foo: 3}, {foo: 4}], 'foo')).toEqualData([{foo: 2}, {foo: 3}, {foo: 4}, {foo: {}}]);
});


it('should perform a stable sort', function() {
expect(orderBy([
{foo: 2, bar: 1}, {foo: 1, bar: 2}, {foo: 2, bar: 3},
{foo: 2, bar: 4}, {foo: 1, bar: 5}, {foo: 2, bar: 6},
{foo: 2, bar: 7}, {foo: 1, bar: 8}, {foo: 2, bar: 9},
{foo: 1, bar: 10}, {foo: 2, bar: 11}, {foo: 1, bar: 12}
], 'foo'))
.toEqualData([
{foo: 1, bar: 2}, {foo: 1, bar: 5}, {foo: 1, bar: 8},
{foo: 1, bar: 10}, {foo: 1, bar: 12}, {foo: 2, bar: 1},
{foo: 2, bar: 3}, {foo: 2, bar: 4}, {foo: 2, bar: 6},
{foo: 2, bar: 7}, {foo: 2, bar: 9}, {foo: 2, bar: 11}
]);

expect(orderBy([
{foo: 2, bar: 1}, {foo: 1, bar: 2}, {foo: 2, bar: 3},
{foo: 2, bar: 4}, {foo: 1, bar: 5}, {foo: 2, bar: 6},
{foo: 2, bar: 7}, {foo: 1, bar: 8}, {foo: 2, bar: 9},
{foo: 1, bar: 10}, {foo: 2, bar: 11}, {foo: 1, bar: 12}
], 'foo', true))
.toEqualData([
{foo: 2, bar: 11}, {foo: 2, bar: 9}, {foo: 2, bar: 7},
{foo: 2, bar: 6}, {foo: 2, bar: 4}, {foo: 2, bar: 3},
{foo: 2, bar: 1}, {foo: 1, bar: 12}, {foo: 1, bar: 10},
{foo: 1, bar: 8}, {foo: 1, bar: 5}, {foo: 1, bar: 2}
]);
});
});


Expand Down

0 comments on commit ed3a33a

Please sign in to comment.