JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
function createStringFunction(argNames, bodyCode) {
const code = `
onmessage = function (event) {
const response = execute(...event.data.args)
postMessage({ callId: event.data.callId, response })
}
function execute(${argNames.join(", ")}) {
${bodyCode}
}
`
const blob = new Blob([code], { type: "text/javascript" })
const worker = new Worker(URL.createObjectURL(blob))
let listeners = {}
worker.onmessage = function (event) {
listeners[event.data.callId](event.data.response)
}
return function (...args) {
return new Promise((resolve, reject) => {
const callId = Math.random().toString(16).slice(2)
listeners[callId] = resolve
worker.postMessage({ callId, args })
})
}
}
const f = createStringFunction(["answer", "question"], `
const { sum } = answer
const { a, b } = question
return sum === a + b
`)
console.log(f({ sum: 3 }, { a: 1, b: 2 }))
console.log(f({ sum: 4 }, { a: 1, b: 2 }))
console.log(f({ sum: 5 }, { a: 3, b: 2 }))