-
Notifications
You must be signed in to change notification settings - Fork 10
/
web-worker.ts
77 lines (64 loc) · 2.53 KB
/
web-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
import {IWebWorkerService} from './web-worker.interface';
export class WebWorkerService implements IWebWorkerService {
private workerFunctionToUrlMap = new WeakMap<Function, string>();
private promiseToWorkerMap = new WeakMap<Promise<any>, Worker>();
run<T>(workerFunction: (input: any) => T, data?: any): Promise<T> {
const url = this.getOrCreateWorkerUrl(workerFunction);
return this.runUrl(url, data);
}
runUrl(url: string, data?: any): Promise<any> {
const worker = new Worker(url);
const promise = this.createPromiseForWorker(worker, data);
const promiseCleaner = this.createPromiseCleaner(promise);
this.promiseToWorkerMap.set(promise, worker);
promise
.then(promiseCleaner)
.catch(promiseCleaner);
return promise;
}
terminate<T>(promise: Promise<T>): Promise<T> {
return this.removePromise(promise);
}
getWorker(promise: Promise<any>): Worker {
return this.promiseToWorkerMap.get(promise);
}
private createPromiseForWorker<T>(worker: Worker, data: any) {
return new Promise<T>((resolve, reject) => {
worker.addEventListener('message', (event) => resolve(event.data));
worker.addEventListener('error', reject);
worker.postMessage(data);
});
}
private getOrCreateWorkerUrl(fn: Function): string {
if (!this.workerFunctionToUrlMap.has(fn)) {
const url = this.createWorkerUrl(fn);
this.workerFunctionToUrlMap.set(fn, url);
return url;
}
return this.workerFunctionToUrlMap.get(fn);
}
private createWorkerUrl(resolve: Function): string {
const resolveString = resolve.toString();
const webWorkerTemplate = `
self.addEventListener('message', function(e) {
postMessage((${resolveString})(e.data));
});
`;
const blob = new Blob([webWorkerTemplate], { type: 'text/javascript' });
return URL.createObjectURL(blob);
}
private createPromiseCleaner<T>(promise: Promise<T>) : (input: any) => T {
return (event) => {
this.removePromise(promise);
return event;
};
}
private removePromise<T>(promise: Promise<T>) : Promise<T> {
const worker = this.promiseToWorkerMap.get(promise);
if (worker) {
worker.terminate();
}
this.promiseToWorkerMap.delete(promise);
return promise;
}
}