DEV Community

ezzabuzaid
ezzabuzaid

Posted on • Edited on

JavaScript Dart Compute

Dart lang offers an optimistic compute function that can execute a code on a separate isolate(thread) to avoid blocking the main thread or to do heavy computation away from the main thread.

It will "Spawn an isolate, run callback on that isolate, passing it a message, and (eventually) returns the value returned by callback."

In contrast, JavaScript also have threads! or web workers that can
"run scripts in background threads without interfering with the user interface".

hence, we can do compute in JavaScript that will spawn worker, run callback on that worker, passing it a message, and (eventually) returns the value returned by callback."

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;
});
}
view raw compute.js hosted with ❤ by GitHub

Example

function factorial(number) {
  if (number <= 0) {
    return 1;
  } else {
    return (number * factorial(number - 1));
  }
};

await compute(factorial, 200);
Enter fullscreen mode Exit fullscreen mode

References
"https://lnkd.in/d5PVjji"
"https://lnkd.in/dqqdBHt"

Retry later

Top comments (0)

Retry later