-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
SearchWorker.worker.ts
96 lines (77 loc) · 1.97 KB
/
SearchWorker.worker.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import * as lunr from 'lunr';
try {
// tslint:disable-next-line
require('core-js/es/promise'); // bundle into worker
} catch (_) {
// nope
}
/* just for better typings */
export default class Worker {
add: typeof add = add;
done = done;
search: typeof search = search;
toJS = toJS;
load = load;
}
export interface SearchDocument {
title: string;
description: string;
id: string;
}
export interface SearchResult<T = string> {
meta: T;
score: number;
}
let store: any[] = [];
let resolveIndex: (v: lunr.Index) => void = () => {
throw new Error('Should not be called');
};
const index: Promise<lunr.Index> = new Promise(resolve => {
resolveIndex = resolve;
});
lunr.tokenizer.separator = /\s+/;
const builder = new lunr.Builder();
builder.field('title');
builder.field('description');
builder.ref('ref');
builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);
const expandTerm = term => '*' + lunr.stemmer(new lunr.Token(term, {})) + '*';
export function add<T>(title: string, description: string, meta?: T) {
const ref = store.push(meta) - 1;
const item = { title: title.toLowerCase(), description: description.toLowerCase(), ref };
builder.add(item);
}
export async function done() {
resolveIndex(builder.build());
}
export async function toJS() {
return {
store,
index: (await index).toJSON(),
};
}
export async function load(state: any) {
store = state.store;
resolveIndex(lunr.Index.load(state.index));
}
export async function search<Meta = string>(
q: string,
limit = 0,
): Promise<Array<SearchResult<Meta>>> {
if (q.trim().length === 0) {
return [];
}
let searchResults = (await index).query(t => {
q.trim()
.toLowerCase()
.split(/\s+/)
.forEach(term => {
const exp = expandTerm(term);
t.term(exp, {});
});
});
if (limit > 0) {
searchResults = searchResults.slice(0, limit);
}
return searchResults.map(res => ({ meta: store[res.ref], score: res.score }));
}