Last active
May 6, 2024 10:44
-
-
Save mayank99/51d27c0037ffe9150adfdfe2244039d9 to your computer and use it in GitHub Desktop.
Create a web worker in the same file where it's used
This file contains hidden or 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 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