-
Notifications
You must be signed in to change notification settings - Fork 114
/
UnorderedSearchIndex.js
75 lines (57 loc) · 1.9 KB
/
UnorderedSearchIndex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// @flow
import type { ISearchIndex } from './SearchIndex';
/**
* Search index capable of returning results matching a set of tokens but without any meaningful rank or order.
*/
export class UnorderedSearchIndex implements ISearchIndex {
_tokenToUidToDocumentMap : {[token : string] : {[uid : string] : any}};
constructor() {
this._tokenToUidToDocumentMap = {};
}
/**
* @inheritDocs
*/
indexDocument(token : string, uid : string, doc : Object) : void {
if (typeof this._tokenToUidToDocumentMap[token] !== 'object') {
this._tokenToUidToDocumentMap[token] = {};
}
this._tokenToUidToDocumentMap[token][uid] = doc;
}
/**
* @inheritDocs
*/
search(tokens : Array<string>, corpus : Array<Object>) : Array<Object> {
var intersectingDocumentMap = {};
var tokenToUidToDocumentMap = this._tokenToUidToDocumentMap;
for (var i = 0, numTokens = tokens.length; i < numTokens; i++) {
var token = tokens[i];
var documentMap = tokenToUidToDocumentMap[token];
// Short circuit if no matches were found for any given token.
if (!documentMap) {
return [];
}
if (i === 0) {
var keys = Object.keys(documentMap);
for (var j = 0, numKeys = keys.length; j < numKeys; j++) {
var uid = keys[j];
intersectingDocumentMap[uid] = documentMap[uid];
}
} else {
var keys = Object.keys(intersectingDocumentMap);
for (var j = 0, numKeys = keys.length; j < numKeys; j++) {
var uid = keys[j];
if (typeof documentMap[uid] !== 'object') {
delete intersectingDocumentMap[uid];
}
}
}
}
var keys = Object.keys(intersectingDocumentMap);
var documents = [];
for (var i = 0, numKeys = keys.length; i < numKeys; i++) {
var uid = keys[i];
documents.push(intersectingDocumentMap[uid]);
}
return documents;
}
};