Skip to content

Instantly share code, notes, and snippets.

@mayank99
Last active May 6, 2024 10:44
Show Gist options
  • Save mayank99/51d27c0037ffe9150adfdfe2244039d9 to your computer and use it in GitHub Desktop.
Save mayank99/51d27c0037ffe9150adfdfe2244039d9 to your computer and use it in GitHub Desktop.
Create a web worker in the same file where it's used
function createWorker(fn) {
const url = URL.createObjectURL(
new Blob([`\
onmessage = ({ data }) => {
const fn = ${fn.toString()};
const result = fn(...JSON.parse(data));
self.postMessage(result);
};
`])
);
const worker = new Worker(url);
URL.revokeObjectURL(url);
return (...args) => new Promise((resolve, reject) => {
const message = JSON.stringify([...args]);
worker.onmessage = ({ data }) => resolve(data);
worker.postMessage(message);
});
}
// Usage:
const sum = createWorker((a, b) => {
if (a === 2 && b === 2) return 5;
return a + b;
});
const result = await sum(2, 2);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment