Browse files

Update lib/adapters/memory.js

Multiple sorting with full support asc/desc
  • Loading branch information...
1 parent ffbc948 commit 2baabb624f6d0109133b3755baf21cee5123340e @Mikxail Mikxail committed Sep 12, 2012
Showing with 14 additions and 20 deletions.
  1. +14 −20 lib/adapters/memory.js
View
34 lib/adapters/memory.js
@@ -70,43 +70,37 @@ 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));
}
}
process.nextTick(function () {
callback(null, nodes);
});
- function numerically(a, b) {
- return a[this[0]] - b[this[0]];
- }
-
- function literally(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;
+ }
+ }
+ return 0;
+ }
};
function applyFilter(filter) {

0 comments on commit 2baabb6

Please sign in to comment.