diff --git a/inverted-index.js b/inverted-index.js index a352d19..8e2ff62 100644 --- a/inverted-index.js +++ b/inverted-index.js @@ -163,8 +163,8 @@ InvertedIndex.prototype.get = function(query) { InvertedIndex.prototype.forEach = function(callback, scope) { scope = arguments.length > 1 ? scope : this; - for (var i = 0, l = this.documents.length; i < l; i++) - callback.call(scope, this.documents[i], i, this); + for (var i = 0, l = this.items.length; i < l; i++) + callback.call(scope, this.items[i], i, this); }; /** diff --git a/test/inverted-index.js b/test/inverted-index.js index 97ed01f..d5d9c03 100644 --- a/test/inverted-index.js +++ b/test/inverted-index.js @@ -90,12 +90,47 @@ describe('InvertedIndex', function() { }); it('should be possible to iterate using #.forEach', function() { - var index = InvertedIndex.from(DOCS, tokenizer); + var index = InvertedIndex.from(DOCS, tokenizer), + visited = []; index.forEach(function(doc, i, instance) { + assert.strictEqual(this, index); assert.strictEqual(instance, index); + assert.strictEqual(i, visited.length); assert.strictEqual(doc, DOCS[i]); + visited.push(doc); }); + + assert.deepStrictEqual(visited, DOCS); + }); + + it('should be possible to provide a scope to #.forEach.', function() { + var index = InvertedIndex.from(OBJECT_DOCS, documentTokenizer), + scope = {documents: []}; + + index.forEach(function(doc, i, instance) { + assert.strictEqual(this, scope); + assert.strictEqual(instance, index); + assert.strictEqual(i, this.documents.length); + assert.strictEqual(doc, OBJECT_DOCS[i]); + this.documents.push(doc); + }, scope); + + assert.deepStrictEqual(scope.documents, OBJECT_DOCS); + }); + + it('should not call the #.forEach callback on an empty index.', function() { + var index = new InvertedIndex(tokenizer); + + function fail() { + assert.fail('An empty index should not call the callback.'); + } + + index.forEach(fail); + + index.add(DOCS[0]); + index.clear(); + index.forEach(fail); }); it('should be possible to create an iterator over documents.', function() {