-
Notifications
You must be signed in to change notification settings - Fork 1
/
wrun.js
45 lines (38 loc) · 1.18 KB
/
wrun.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
function wrun(fn, wtype = 'Worker') {
const result = (worker, error) => ({ worker, error });
if (typeof window === 'undefined') {
return result(null, {
code: 1,
message: 'The current scope has no "window" object available.'
});
}
if (!hasOwnProperty.call(window, 'Blob') || !hasOwnProperty.call(window, 'URL')) {
return result(null, {
code: 2,
message: 'The current application is not compatible with "wrun".'
});
}
if (!hasOwnProperty.call(window, wtype)) {
return result(null, {
code: 3,
message: `The worker type "${wtype}" does not exists on the current scope`
});
}
if (typeof fn !== 'function') {
return result(null, {
code: 4,
message: `The wrun argument must be a function`
});
}
try {
const blob = new window.Blob([ `(${fn.toString()})()` ], { type: 'application/javascript' });
const swObjectURL = window.URL.createObjectURL(blob);
const worker = new window[wtype](swObjectURL);
return result(worker, false);
} catch(error) {
return result(null, { code: 0, error: error.message });
}
}
if (typeof module !== 'undefined') {
module.exports = wrun;
}