Can update documents in the index

pull/2/head
Louis Chatriot 12 years ago
parent abbaa1d308
commit 16cf75b70d
  1. 11
      lib/indexes.js
  2. 30
      test/indexes.test.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;

@ -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' ==== //
});

Loading…
Cancel
Save