diff --git a/lib/indexes.js b/lib/indexes.js index de22638..d8e4f84 100644 --- a/lib/indexes.js +++ b/lib/indexes.js @@ -33,6 +33,7 @@ function Index (options) { /** * Insert a new document in the index + * O(log(n)) */ Index.prototype.insert = function (doc) { var key = model.getDotValue(doc, this.fieldName); @@ -49,6 +50,7 @@ Index.prototype.insert = function (doc) { /** * Remove a document from the index + * O(log(n)) */ Index.prototype.remove = function (doc) { var key = model.getDotValue(doc, this.fieldName); @@ -62,6 +64,15 @@ Index.prototype.remove = function (doc) { }; +/** + * Update a document in the index + * O(log(n)) + */ +Index.prototype.update = function (oldDoc, newDoc) { + this.remove(oldDoc); + this.insert(newDoc); +}; + // Interface module.exports = Index; diff --git a/test/indexes.test.js b/test/indexes.test.js index 4b2eca0..8d09100 100644 --- a/test/indexes.test.js +++ b/test/indexes.test.js @@ -116,4 +116,34 @@ describe('Indexing', function () { }); // ==== End of 'Removal' ==== // + + describe('Update', function () { + + it('Can update a document whose key did or didnt change', function () { + var idx = new Index({ fieldName: 'tf' }) + , doc1 = { a: 5, tf: 'hello' } + , doc2 = { a: 8, tf: 'world' } + , doc3 = { a: 2, tf: 'bloup' } + , doc4 = { a: 23, tf: 'world' } + , doc5 = { a: 1, tf: 'changed' } + ; + + idx.insert(doc1); + idx.insert(doc2); + idx.insert(doc3); + idx.tree.getNumberOfKeys().should.equal(3); + assert.deepEqual(idx.tree.search('world'), [doc2]); + + idx.update(doc2, doc4); + idx.tree.getNumberOfKeys().should.equal(3); + assert.deepEqual(idx.tree.search('world'), [doc4]); + + idx.update(doc1, doc5); + idx.tree.getNumberOfKeys().should.equal(3); + assert.deepEqual(idx.tree.search('hello'), []); + assert.deepEqual(idx.tree.search('changed'), [doc5]); + }); + + }); // ==== End of 'Update' ==== // + });