-
-
Notifications
You must be signed in to change notification settings - Fork 493
/
index.js
157 lines (108 loc) · 3.05 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//import { promise as Promise } from "../polyfill.js";
import { create_object, is_function, is_object, is_string } from "../common.js";
import handler from "./handler.js";
let pid = 0;
/**
* @param {Object=} options
* @constructor
*/
function WorkerIndex(options){
if(!(this instanceof WorkerIndex)) {
return new WorkerIndex(options);
}
let opt;
if(options){
if(is_function(opt = options["encode"])){
options["encode"] = opt.toString();
}
}
else{
options = {};
}
// the factory is the outer wrapper from the build
// we use "self" as a trap for node.js
let factory = (self||window)["_factory"];
if(factory){
factory = factory.toString();
}
const is_node_js = typeof window === "undefined" && self["exports"];
const _self = this;
this.worker = create(factory, is_node_js, options["worker"]);
this.resolver = create_object();
if(!this.worker){
return;
}
if(is_node_js){
this.worker["on"]("message", function(msg){
_self.resolver[msg["id"]](msg["msg"]) ;
delete _self.resolver[msg["id"]];
});
}
else{
this.worker.onmessage = function(msg){
msg = msg["data"];
_self.resolver[msg["id"]](msg["msg"]);
delete _self.resolver[msg["id"]];
};
}
this.worker.postMessage({
"task": "init",
"factory": factory,
"options": options
});
}
export default WorkerIndex;
register("add");
register("append");
register("search");
register("update");
register("remove");
function register(key){
WorkerIndex.prototype[key] =
WorkerIndex.prototype[key + "Async"] = function(){
const self = this;
const args = [].slice.call(arguments);
const arg = args[args.length - 1];
let callback;
if(is_function(arg)){
callback = arg;
args.splice(args.length - 1, 1);
}
const promise = new Promise(function(resolve){
setTimeout(function(){
self.resolver[++pid] = resolve;
self.worker.postMessage({
"task": key,
"id": pid,
"args": args
});
});
});
if(callback){
promise.then(callback);
return this;
}
else{
return promise;
}
};
}
function create(factory, is_node_js, worker_path){
let worker
try{
worker = is_node_js ?
eval('new (require("worker_threads")["Worker"])(__dirname + "/node/node.js")')
:(
factory ?
new Worker(URL.createObjectURL(
new Blob([
"onmessage=" + handler.toString()
], { "type": "text/javascript" })
))
:
new Worker(is_string(worker_path) ? worker_path : "worker/worker.js", { type: "module" })
);
}
catch(e){}
return worker;
}