Merge pull request #379 from cvette/memory-order-fix

fix sorting of undefined values in memory connector
This commit is contained in:
Raymond Feng 2015-01-06 09:39:49 -08:00
commit eac7526e80
2 changed files with 22 additions and 6 deletions

View File

@ -347,13 +347,19 @@ Memory.prototype.all = function all(model, filter, callback) {
}); });
function sorting(a, b) { function sorting(a, b) {
var undefinedA, undefinedB;
for (var i = 0, l = this.length; i < l; i++) { for (var i = 0, l = this.length; i < l; i++) {
if (a[this[i].key] > b[this[i].key]) { undefinedB = b[this[i].key] === undefined && a[this[i].key] !== undefined;
undefinedA = a[this[i].key] === undefined && b[this[i].key] !== undefined;
if (undefinedB || a[this[i].key] > b[this[i].key]) {
return 1 * this[i].reverse; return 1 * this[i].reverse;
} else if (a[this[i].key] < b[this[i].key]) { } else if (undefinedA || a[this[i].key] < b[this[i].key]) {
return -1 * this[i].reverse; return -1 * this[i].reverse;
} }
} }
return 0; return 0;
} }
}; };

View File

@ -183,7 +183,7 @@ describe('Memory connector', function () {
}); });
}); });
it('support order with multiple fields', function (done) { it('should support order with multiple fields', function (done) {
User.find({order: 'vip ASC, seq DESC'}, function (err, posts) { User.find({order: 'vip ASC, seq DESC'}, function (err, posts) {
should.not.exist(err); should.not.exist(err);
posts[0].seq.should.be.eql(4); posts[0].seq.should.be.eql(4);
@ -192,6 +192,17 @@ describe('Memory connector', function () {
}); });
}); });
it('should sort undefined values to the end when ordered DESC', function (done) {
User.find({order: 'vip ASC, order DESC'}, function (err, posts) {
console.log(posts);
should.not.exist(err);
posts[4].seq.should.be.eql(1);
posts[5].seq.should.be.eql(0);
done();
});
});
it('should throw if order has wrong direction', function (done) { it('should throw if order has wrong direction', function (done) {
User.find({order: 'seq ABC'}, function (err, posts) { User.find({order: 'seq ABC'}, function (err, posts) {
should.exist(err); should.exist(err);
@ -200,11 +211,11 @@ describe('Memory connector', function () {
}); });
it('should support neq operator for number', function (done) { it('should support neq operator for number', function (done) {
User.find({where: {order: {neq: 6}}}, function (err, users) { User.find({where: {seq: {neq: 4}}}, function (err, users) {
should.not.exist(err); should.not.exist(err);
users.length.should.be.equal(5); users.length.should.be.equal(5);
for (var i = 0; i < users.length; i++) { for (var i = 0; i < users.length; i++) {
users[i].order.should.not.be.equal(6); users[i].seq.should.not.be.equal(4);
} }
done(); done();
}); });
@ -242,7 +253,6 @@ describe('Memory connector', function () {
email: 'john@b3atl3s.co.uk', email: 'john@b3atl3s.co.uk',
role: 'lead', role: 'lead',
birthday: new Date('1980-12-08'), birthday: new Date('1980-12-08'),
order: 2,
vip: true vip: true
}, },
{ {