Skip to content

Commit

Permalink
Make default comparison treat null and undefined the same as Array.sort
Browse files Browse the repository at this point in the history
Fixes dojo#131 by making the default comparison function created
in _createSortQuerier treat undefined as greater than any
value, and null greater than any other value.
  • Loading branch information
maier49 committed Jun 30, 2015
1 parent f277b48 commit 7946d17
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
13 changes: 9 additions & 4 deletions SimpleQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ define([
data.sort(typeof sorted == 'function' ? sorted : function (a, b) {
for (var i = 0; i < sorted.length; i++) {
var comparison;
var isALessThanB;
var sorter = sorted[i];
if (typeof sorter == 'function') {
comparison = sorter(a, b);
Expand All @@ -184,10 +185,14 @@ define([

aValue != null && (aValue = aValue.valueOf());
bValue != null && (bValue = bValue.valueOf());

comparison = aValue === bValue
? 0
: (!!descending === (aValue === null || aValue > bValue && bValue !== null) ? -1 : 1);
if (aValue === bValue) {
comparison = 0;
}
else {
isALessThanB = aValue < bValue || typeof bValue === 'undefined' ||
bValue === null && typeof aValue !== 'undefined';
comparison = !!descending === isALessThanB ? 1 : -1
}
}

if (comparison !== 0) {
Expand Down
28 changes: 28 additions & 0 deletions tests/SimpleQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,34 @@ define([
]);
},

'sort null and undefined': function () {
var sort = simpleQuery._createSortQuerier([ { property: 'name' } ]);
var sortDescending = simpleQuery._createSortQuerier([ { descending: true, property: 'name' } ]);
var data = testData.slice();
data.splice(2 , 0, { id: 7, odd: false });
data.splice(2, 0, { id: 6, name: null, odd: true });

assert.deepEqual(sort(data), [
{ id: 5, name: 'five', odd: true },
{ id: 4, name: 'four', odd: false },
{ id: 1, name: 'one', odd: true },
{ id: 3, name: 'three', odd: true },
{ id: 2, name: 'two', odd: false },
{ id: 6, name: null, odd: true },
{ id: 7, odd: false }
]);

assert.deepEqual(sortDescending(data), [
{ id: 7, odd: false },
{ id: 6, name: null, odd: true },
{ id: 2, name: 'two', odd: false },
{ id: 3, name: 'three', odd: true },
{ id: 1, name: 'one', odd: true },
{ id: 4, name: 'four', odd: false },
{ id: 5, name: 'five', odd: true }
]);
},

'nested queries': function () {
var f = new Filter();
var isEven = f.eq('odd', false);
Expand Down

0 comments on commit 7946d17

Please sign in to comment.