From db1cc10202d6357434bdcea0d6bb830fa924a160 Mon Sep 17 00:00:00 2001 From: Louis Chatriot Date: Sun, 20 Oct 2013 12:27:20 +0200 Subject: [PATCH] Type-checking projection function --- lib/indexes.js | 15 ++++++++++++++- test/indexes.test.js | 12 ++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/indexes.js b/lib/indexes.js index 05866f2..89d988c 100644 --- a/lib/indexes.js +++ b/lib/indexes.js @@ -11,6 +11,19 @@ function checkValueEquality (a, b) { return a === b; } +/** + * Type-aware projection + */ +function projectForUnique (elt) { + if (elt === null) { return '$null'; } + if (typeof elt === 'string') { return '$string' + elt; } + if (typeof elt === 'boolean') { return '$boolean' + elt; } + if (typeof elt === 'number') { return '$number' + elt; } + if (util.isArray(elt)) { return '$date' + elt.getTime(); } + + return elt; // Arrays and objects, will check for pointer equality +} + /** * Create a new index @@ -61,7 +74,7 @@ Index.prototype.insert = function (doc) { if (!util.isArray(key)) { this.tree.insert(key, doc); } else { - _.uniq(key, model.areThingsEqual).forEach(function (_key) { + _.uniq(key, projectForUnique).forEach(function (_key) { self.tree.insert(_key, doc); }); } diff --git a/test/indexes.test.js b/test/indexes.test.js index 6c9b864..c2482ba 100644 --- a/test/indexes.test.js +++ b/test/indexes.test.js @@ -137,6 +137,18 @@ describe('Indexes', function () { idx.insert(obj2); idx.getAll().length.should.equal(3); }); + + it('Inserts one entry per array element in the index, type-checked', function () { + var obj = { tf: ['42', 42, new Date(42), 42], really: 'yeah' } + , idx = new Index({ fieldName: 'tf' }) + ; + + idx.insert(obj); + idx.getAll().length.should.equal(3); + idx.getAll()[0].should.equal(obj); + idx.getAll()[1].should.equal(obj); + idx.getAll()[2].should.equal(obj); + }); it('Inserts one entry per unique array element in the index, the unique constraint only holds across documents', function () { var obj = { tf: ['aa', 'aa'], really: 'yeah' }