Implement first-round sorting in memory adapter

This commit is contained in:
Anatoliy Chakkaev 2012-01-19 17:44:11 +04:00
parent f0a34bf008
commit f21b3f2a43
1 changed files with 38 additions and 1 deletions

View File

@ -45,9 +45,46 @@ Memory.prototype.all = function all(model, filter, callback) {
var nodes = Object.keys(this.cache[model]).map(function (key) {
return this.cache[model][key];
}.bind(this));
process.nextTick(function () {
callback(null, filter && nodes ? nodes.filter(applyFilter(filter)) : nodes);
if (filter) {
// do we need some filtration?
if (filter.where) {
nodes = nodes ? nodes.filter(applyFilter(filter)) : nodes;
}
// do we need some sorting?
if (filter.order) {
var props = this._models[model].properties;
var allNumeric = true;
var orders = filter.order;
if (typeof filter.order === "string") {
orders = [filter.order];
}
orders.forEach(function (key) {
if (props[key].type.name !== 'Number' && props[key].type.name !== 'Date') {
allNumeric = false;
}
});
if (allNumeric) {
nodes = nodes.sort(numerically.bind(orders));
} else {
nodes = nodes.sort(literally.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 applyFilter(filter) {