Skip to content

Commit 3ff507b

Browse files
committed
Size optimizations
1 parent 9b4337b commit 3ff507b

File tree

1 file changed

+28
-32
lines changed

1 file changed

+28
-32
lines changed

src/index.js

Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -37,53 +37,49 @@ export default function workerize(code, options) {
3737
};
3838
worker.terminate = () => {
3939
URL.revokeObjectURL(url);
40-
term();
40+
term.call(this);
4141
};
42-
worker.rpcMethods = {};
43-
function setup(ctx, rpcMethods, callbacks) {
44-
ctx.addEventListener('message', ({ data }) => {
45-
if (data.type==='RPC') {
46-
let id = data.id;
47-
if (id!=null) {
48-
if (data.method) {
49-
let method = rpcMethods[data.method];
50-
if (method==null) {
51-
ctx.postMessage({ type: 'RPC', id, error: 'NO_SUCH_METHOD' });
52-
}
53-
else {
54-
Promise.resolve()
55-
.then( () => method.apply(null, data.params) )
56-
.then( result => { ctx.postMessage({ type: 'RPC', id, result }); })
57-
.catch( error => { ctx.postMessage({ type: 'RPC', id, error }); });
58-
}
59-
}
60-
else {
61-
let callback = callbacks[id];
62-
if (callback==null) throw Error(`Unknown callback ${id}`);
63-
delete callbacks[id];
64-
if (data.error) callback.reject(Error(data.error));
65-
else callback.resolve(data.result);
66-
}
67-
}
68-
}
69-
});
70-
}
71-
setup(worker, worker.rpcMethods, callbacks);
7242
worker.call = (method, params) => new Promise( (resolve, reject) => {
7343
let id = `rpc${++counter}`;
74-
callbacks[id] = { method, resolve, reject };
44+
callbacks[id] = [resolve, reject];
7545
worker.postMessage({ type: 'RPC', id, method, params });
7646
});
7747
for (let i in exports) {
7848
if (exports.hasOwnProperty(i) && !(i in worker)) {
7949
worker[i] = (...args) => worker.call(i, args);
8050
}
8151
}
52+
worker.rpcMethods = {};
53+
setup(worker, worker.rpcMethods, callbacks);
8254
return worker;
8355
}
8456

8557
function toCode(func) {
8658
return Function.prototype.toString.call(func);
59+
function setup(ctx, rpcMethods, callbacks) {
60+
ctx.addEventListener('message', ({ data }) => {
61+
let id = data.id;
62+
if (data.type!=='RPC' || id==null) return;
63+
if (data.method) {
64+
let method = rpcMethods[data.method];
65+
if (method==null) {
66+
ctx.postMessage({ type: 'RPC', id, error: 'NO_SUCH_METHOD' });
67+
}
68+
else {
69+
Promise.resolve()
70+
.then( () => method.apply(null, data.params) )
71+
.then( result => { ctx.postMessage({ type: 'RPC', id, result }); })
72+
.catch( error => { ctx.postMessage({ type: 'RPC', id, error }); });
73+
}
74+
}
75+
else {
76+
let callback = callbacks[id];
77+
if (callback==null) throw Error(`Unknown callback ${id}`);
78+
delete callbacks[id];
79+
if (data.error) callback[1](Error(data.error));
80+
else callback[0](data.result);
81+
}
82+
});
8783
}
8884

8985
function toCjs(code, exportsObjName, exports) {

0 commit comments

Comments
 (0)