This repository was archived by the owner on Nov 1, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathsearch_worker.js
More file actions
58 lines (48 loc) · 1.66 KB
/
search_worker.js
File metadata and controls
58 lines (48 loc) · 1.66 KB
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
importScripts('lunr.min.js');
// create lunr.js search index specifying that we want to index the title and body fields of documents.
var lunr_index = lunr(function() {
this.field('title', { boost: 10 });
this.field('body');
this.ref('id');
}),
entries;
onmessage = function (oEvent) {
populateIndex = function(data) {
// format the raw json into a form that is simpler to work with
this.entries = data.map(this.createEntry).filter(function(n){ return n !== undefined });
this.entries.forEach(function(entry) {
if (entry !== null)
this.lunr_index.add(entry);
});
postMessage({type: {indexed: true}});
};
decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
createEntry = function(entry, entry_id) {
if (entry.title === undefined)
return undefined;
entry.id = entry_id + 1;
entry.title = decodeHtmlEntity(entry.title);
return entry;
};
search = function(data) {
var entries = this.entries;
var results = lunr_index
.search(data.query)
.map(function(result) {
return entries.filter(function(entry) { return entry.id === parseInt(result.ref, 10); })[0];
})
.filter(function (result) {
return typeof result !== 'undefined';
});
postMessage({ query: data.query, results: results, type: { search: true } });
}
// if we're asked to index, index! else, search
if (oEvent.data.type == "index")
populateIndex(oEvent.data);
else
search(oEvent.data);
};