From f21b3f2a4391eeb89c979b1b5a313e068c0e587e Mon Sep 17 00:00:00 2001 From: Anatoliy Chakkaev Date: Thu, 19 Jan 2012 17:44:11 +0400 Subject: [PATCH] Implement first-round sorting in memory adapter --- lib/adapters/memory.js | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/adapters/memory.js b/lib/adapters/memory.js index f7e76c51..2e040c0b 100644 --- a/lib/adapters/memory.js +++ b/lib/adapters/memory.js @@ -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)); + + 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, filter && nodes ? nodes.filter(applyFilter(filter)) : nodes); + 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) {