From a0a9fae9c6856d4142516c4099de5aaa7d9b7919 Mon Sep 17 00:00:00 2001 From: Raymond Feng Date: Fri, 6 Jun 2014 08:19:41 -0700 Subject: [PATCH] Enhance comparators for memory connector --- lib/connectors/memory.js | 55 +++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/lib/connectors/memory.js b/lib/connectors/memory.js index ce466221..670ece80 100644 --- a/lib/connectors/memory.js +++ b/lib/connectors/memory.js @@ -377,24 +377,61 @@ function applyFilter(filter) { } if (example.inq) { - if (!value) return false; - for (var i = 0; i < example.inq.length; i += 1) { - if (example.inq[i] == value) return true; + // if (!value) return false; + for (var i = 0; i < example.inq.length; i++) { + if (example.inq[i] == value) { + return true; + } } return false; } - if (isNum(example.gt) && example.gt < value) return true; - if (isNum(example.gte) && example.gte <= value) return true; - if (isNum(example.lt) && example.lt > value) return true; - if (isNum(example.lte) && example.lte >= value) return true; + if (testInEquality(example, value)) { + return true; + } } // not strict equality return (example !== null ? example.toString() : example) == (value !== null ? value.toString() : value); } - function isNum(n) { - return typeof n === 'number'; + /** + * Compare two values + * @param {*} val1 The 1st value + * @param {*} val2 The 2nd value + * @returns {number} 0: =, postive: >, negative < + * @private + */ + function compare(val1, val2) { + if (typeof val1 === 'number') { + return val1 - val2; + } + if (typeof val1 === 'string') { + return (val1 > val2) ? 1 : ((val1 < val2) ? -1 : 0); + } + if (typeof val1 === 'boolean') { + return val1 - val2; + } + if (val1 instanceof Date) { + return val1.getTime() - ((val2 && val2.getTime()) || 0); + } + // Return NaN if we don't know how to compare + return (val1 === val2) ? 0 : NaN; + } + + function testInEquality(example, val) { + if ('gt' in example) { + return compare(example.gt, val) > 0; + } + if ('gte' in example) { + return compare(example.gte, val) >= 0; + } + if ('lt' in example) { + return compare(example.lt, val) < 0; + } + if ('lte' in example) { + return compare(example.lte, val) <= 0; + } + return false; } }