Skip to content

Instantly share code, notes, and snippets.

@MatthewRiggott
Created June 1, 2019 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewRiggott/4b1f967659f571373b57044af4568f92 to your computer and use it in GitHub Desktop.
Save MatthewRiggott/4b1f967659f571373b57044af4568f92 to your computer and use it in GitHub Desktop.
Run string as Function with args from web worker
sendCode() {
const code = this.state.code;
const lastRowIndex = this.refs.aceEditor.editor.session.getLength() - 1;
const functionBody = code.split('\n').filter((l, i) => { if(!(i == 0 || i == lastRowIndex )){ return l } }).join("\n");
const question = this.state.question;
const functionName = question.functionName;
const params = question.args.map(q => q.name);
const testArgs = question.tests.map(t => t.input);
const interpreter = new Worker();
interpreter.onmessage = (e) => { this.getCodeResult(e) }
this.timeout = setTimeout((() => {
this.getCodeResult({
data: {
result: null,
error: 'Function timed out'
},
})
}).bind(this), 6000);
interpreter.postMessage({ params, functionName, code: functionBody, args: testArgs });
}
onmessage = (e) => {
console.log("data" + e.data);
console.log("code: "+ e.data.code);
console.log("argsCount: " + e.data.args[0].length);
try {
const name = e.data.functionName;
this[name] = Function(...e.data.params, e.data.code);
const argArray = e.data.args;
let results = [];
let errors = [];
for(let i = 0; i < argArray.length; i++){
const args = argArray[i];
let result;
try {
result = { value: this[name](...args) };
} catch(testException) {
result = { error: `Error executing function with ${JSON.stringify(args)}: ${testException.message}` };
}
const response = Object.assign({ args }, { result });
results.push(response);
}
postMessage({ results, errors });
} catch(ex) {
postMessage({ results: null, error: [`Error building function: ${ex.message}`] });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment