From 497c487be5337ffe7333b3d624d2ab9c5501693c Mon Sep 17 00:00:00 2001 From: heisaf Date: Tue, 20 Jan 2015 11:44:45 +0100 Subject: [PATCH] fix(orderBy): ensure the orderBy formatter can handle null values in collections --- lib/formatter/order_by.dart | 8 +++++- test/formatter/order_by_spec.dart | 41 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/lib/formatter/order_by.dart b/lib/formatter/order_by.dart index f39ee9f83..ad76fbf9d 100644 --- a/lib/formatter/order_by.dart +++ b/lib/formatter/order_by.dart @@ -139,7 +139,13 @@ class OrderBy implements Function { static _nop(e) => e; static bool _isNonZero(int n) => (n != 0); static int _returnZero() => 0; - static int _defaultComparator(a, b) => Comparable.compare(a, b); + static int _defaultComparator(a, b) { + if (a == null && b == null) return 0; + if (a == null) return -1; + if (b == null) return 1; + + return Comparable.compare(a, b); + } static int _reverseComparator(a, b) => _defaultComparator(b, a); static int _compareLists(List a, List b, List comparators) { diff --git a/test/formatter/order_by_spec.dart b/test/formatter/order_by_spec.dart index 4dde657c0..777cca41d 100644 --- a/test/formatter/order_by_spec.dart +++ b/test/formatter/order_by_spec.dart @@ -201,4 +201,45 @@ main() { }); }); + + describe('null safe orderBy formatter', () { + var Emily___Bronte = new Name(firstName: 'Emily', lastName: 'Bronte'), + Mark____Twain = {'firstName': 'Mark', 'lastName': 'Twain'}, + Jeffrey_Archer = {'firstName': 'Jeffrey', 'lastName': 'Archer'}, + Isaac___Asimov = new Name(firstName: 'Isaac', lastName: 'Asimov'), + Oscar___Wilde = {'firstName': 'Oscar', 'lastName': 'Wilde'}, + Oscar___Null = {'firstName': 'Oscar', 'lastName': null}; + beforeEach((Scope scope, Parser parse, FormatterMap formatters) { + scope.context['authors'] = [ + Emily___Bronte, + Mark____Twain, + Jeffrey_Archer, + Isaac___Asimov, + Oscar___Wilde, + Oscar___Null + ]; + }); + it('should allow null values', + (Scope scope, Parser parse, FormatterMap formatters) { + expect(parse('authors | orderBy:"lastName"').eval(scope.context, formatters)).toEqual([ + Oscar___Null, + Jeffrey_Archer, + Isaac___Asimov, + Emily___Bronte, + Mark____Twain, + Oscar___Wilde, + ]); + }); + it('should allow null values in reverse order', + (Scope scope, Parser parse, FormatterMap formatters) { + expect(parse('authors | orderBy:"-lastName"').eval(scope.context, formatters)).toEqual([ + Oscar___Wilde, + Mark____Twain, + Emily___Bronte, + Isaac___Asimov, + Jeffrey_Archer, + Oscar___Null, + ]); + }); + }); }