Allow partial list of ids for sortByIds

This commit is contained in:
Fabien Franzen 2014-08-14 09:40:03 +02:00
parent 8743d75999
commit 085bb94505
2 changed files with 48 additions and 11 deletions

View File

@ -351,19 +351,29 @@ DataAccessObject.sortByIds = function(ids, results) {
return (typeof id === 'object') ? id.toString() : id;
});
results.sort(function(x, y) {
var idA = (typeof x[pk] === 'object') ? x[pk].toString() : x[pk];
var idB = (typeof y[pk] === 'object') ? y[pk].toString() : y[pk];
var a = ids.indexOf(idA);
var b = ids.indexOf(idB);
if (a === -1 || b === -1) return 1; // last
if (a !== b) {
if (a > b) return 1;
if (a < b) return -1;
}
var indexOf = function(x) {
var id = (typeof x[pk] === 'object') ? x[pk].toString() : x[pk];
return ids.indexOf(id);
};
var heading = [];
var tailing = [];
results.forEach(function(x) {
var idx = indexOf(x);
idx === -1 ? tailing.push(x) : heading.push(x);
});
return results;
heading.sort(function(x, y) {
var a = indexOf(x);
var b = indexOf(y);
if (a === -1 || b === -1) return 1; // last
if (a === b) return 0;
if (a > b) return 1;
if (a < b) return -1;
});
return heading.concat(tailing);
};
function convertNullToNotFoundError(ctx, cb) {

View File

@ -87,6 +87,33 @@ describe('basic-querying', function () {
done();
});
});
it('should sortByIds', function(done) {
User.find(function(err, users) {
sorted = User.sortByIds([6, 5, 4, 3, 2, 1], users);
var names = sorted.map(function(u) { return u.name; });
names.should.eql(['f', 'e', 'd', 'c', 'b', 'a']);
done();
});
});
it('should sortByIds - partial ids (1)', function(done) {
User.find(function(err, users) {
sorted = User.sortByIds([6, 5, 4], users);
var names = sorted.map(function(u) { return u.name; });
names.should.eql(['f', 'e', 'd', 'a', 'b', 'c']);
done();
});
});
it('should sortByIds - partial ids (2)', function(done) {
User.find(function(err, users) {
sorted = User.sortByIds([5, 3, 2], users);
var names = sorted.map(function(u) { return u.name; });
names.should.eql(['e', 'c', 'b', 'a', 'd', 'f']);
done();
});
});
});