Last active
April 17, 2024 05:49
-
-
Save ezzabuzaid/c8c14b2ccddca6a7e16a2cbbc3bac556 to your computer and use it in GitHub Desktop.
Simple inline web worker helper. compute version of Dart in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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