Skip to content
This repository was archived by the owner on Feb 22, 2018. It is now read-only.

Commit 497c487

Browse files
heisafrkirov
authored andcommitted
fix(orderBy): ensure the orderBy formatter can handle null values in collections
1 parent eee5b5e commit 497c487

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

lib/formatter/order_by.dart

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,13 @@ class OrderBy implements Function {
139139
static _nop(e) => e;
140140
static bool _isNonZero(int n) => (n != 0);
141141
static int _returnZero() => 0;
142-
static int _defaultComparator(a, b) => Comparable.compare(a, b);
142+
static int _defaultComparator(a, b) {
143+
if (a == null && b == null) return 0;
144+
if (a == null) return -1;
145+
if (b == null) return 1;
146+
147+
return Comparable.compare(a, b);
148+
}
143149
static int _reverseComparator(a, b) => _defaultComparator(b, a);
144150

145151
static int _compareLists(List a, List b, List<Comparator> comparators) {

test/formatter/order_by_spec.dart

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,4 +201,45 @@ main() {
201201
});
202202

203203
});
204+
205+
describe('null safe orderBy formatter', () {
206+
var Emily___Bronte = new Name(firstName: 'Emily', lastName: 'Bronte'),
207+
Mark____Twain = {'firstName': 'Mark', 'lastName': 'Twain'},
208+
Jeffrey_Archer = {'firstName': 'Jeffrey', 'lastName': 'Archer'},
209+
Isaac___Asimov = new Name(firstName: 'Isaac', lastName: 'Asimov'),
210+
Oscar___Wilde = {'firstName': 'Oscar', 'lastName': 'Wilde'},
211+
Oscar___Null = {'firstName': 'Oscar', 'lastName': null};
212+
beforeEach((Scope scope, Parser parse, FormatterMap formatters) {
213+
scope.context['authors'] = [
214+
Emily___Bronte,
215+
Mark____Twain,
216+
Jeffrey_Archer,
217+
Isaac___Asimov,
218+
Oscar___Wilde,
219+
Oscar___Null
220+
];
221+
});
222+
it('should allow null values',
223+
(Scope scope, Parser parse, FormatterMap formatters) {
224+
expect(parse('authors | orderBy:"lastName"').eval(scope.context, formatters)).toEqual([
225+
Oscar___Null,
226+
Jeffrey_Archer,
227+
Isaac___Asimov,
228+
Emily___Bronte,
229+
Mark____Twain,
230+
Oscar___Wilde,
231+
]);
232+
});
233+
it('should allow null values in reverse order',
234+
(Scope scope, Parser parse, FormatterMap formatters) {
235+
expect(parse('authors | orderBy:"-lastName"').eval(scope.context, formatters)).toEqual([
236+
Oscar___Wilde,
237+
Mark____Twain,
238+
Emily___Bronte,
239+
Isaac___Asimov,
240+
Jeffrey_Archer,
241+
Oscar___Null,
242+
]);
243+
});
244+
});
204245
}

0 commit comments

Comments
 (0)