Update lib/adapters/memory.js
Multiple sorting with full support asc/desc
This commit is contained in:
parent
ffbc9482f7
commit
2baabb624f
|
@ -70,29 +70,20 @@ Memory.prototype.all = function all(model, filter, callback) {
|
|||
// do we need some sorting?
|
||||
if (filter.order) {
|
||||
var props = this._models[model].properties;
|
||||
var allNumeric = true;
|
||||
var orders = filter.order;
|
||||
var reverse = false;
|
||||
if (typeof filter.order === "string") {
|
||||
orders = [filter.order];
|
||||
}
|
||||
orders.forEach(function (key, i) {
|
||||
var reverse = 1;
|
||||
var m = key.match(/\s+(A|DE)SC$/i);
|
||||
if (m) {
|
||||
key = key.replace(/\s+(A|DE)SC/i, '');
|
||||
if (m[1] === 'DE') reverse = true;
|
||||
}
|
||||
orders[i] = key;
|
||||
if (props[key].type.name !== 'Number' && props[key].type.name !== 'Date') {
|
||||
allNumeric = false;
|
||||
if (m[1] === 'DE') reverse = -1;
|
||||
}
|
||||
orders[i] = {"key": key, "reverse": reverse};
|
||||
});
|
||||
if (allNumeric) {
|
||||
nodes = nodes.sort(numerically.bind(orders));
|
||||
} else {
|
||||
nodes = nodes.sort(literally.bind(orders));
|
||||
}
|
||||
if (reverse) nodes = nodes.reverse();
|
||||
nodes = nodes.sort(sorting.bind(orders));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -100,12 +91,15 @@ Memory.prototype.all = function all(model, filter, callback) {
|
|||
callback(null, nodes);
|
||||
});
|
||||
|
||||
function numerically(a, b) {
|
||||
return a[this[0]] - b[this[0]];
|
||||
function sorting(a, b) {
|
||||
for (var i=0, l=this.length; i<l; i++) {
|
||||
if (a[this[i].key] > b[this[i].key]) {
|
||||
return 1*this[i].reverse;
|
||||
} else if (a[this[i].key] < b[this[i].key]) {
|
||||
return -1*this[i].reverse;
|
||||
}
|
||||
|
||||
function literally(a, b) {
|
||||
return a[this[0]] > b[this[0]];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
|
|
Loading…
Reference in New Issue