Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Last active April 17, 2024 05:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezzabuzaid/c8c14b2ccddca6a7e16a2cbbc3bac556 to your computer and use it in GitHub Desktop.
Save ezzabuzaid/c8c14b2ccddca6a7e16a2cbbc3bac556 to your computer and use it in GitHub Desktop.
Simple inline web worker helper. compute version of Dart in JavaScript.
function compute(computation, ...message) {
const delegate = () => {
onmessage = ({ data: { computation, message } }) => {
const wrapper = (fn) => Function('"use strict"; return (' + fn.toString() + ')')();
const result = wrapper(computation)(...message);
postMessage(result);
};
}
const functionBody = delegate.toString().replace(/^[^{]*{\s*/, '').replace(/\s*}[^}]*$/, '');
return new Promise((resolve, reject) => {
const worker = new Worker(URL.createObjectURL(
new Blob([functionBody], { type: 'text/javascript' })
));
worker.onmessage = ({ data }) => {
resolve(data);
worker.terminate();
};
worker.onerror = worker.onmessageerror = reject;
worker.postMessage({ computation: computation.toString(), message });
return worker;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment