Skip to content

Instantly share code, notes, and snippets.

@teak1
Created April 11, 2019 17:42
Show Gist options
  • Save teak1/66e8887a373f2a9eee6eb90e47df3363 to your computer and use it in GitHub Desktop.
Save teak1/66e8887a373f2a9eee6eb90e47df3363 to your computer and use it in GitHub Desktop.
function createOffloadedFunction(...code) {//arg 0 is func and all aditional args are support and loaded in after.
window.URL = window.URL || window.webkitURL;
let func = code.shift();
var response = code.join("\n\n") + `\n\nconst func = ${func.toString()}\n\nself.onmessage=function(pack){self.postMessage({id:pack.data.id,data:func(...pack.data.data)})}\n\n`;
var blob;
try {
blob = new Blob([response], { type: 'application/javascript' });
} catch (e) {
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
blob = new BlobBuilder();
blob.append(response);
blob = blob.getBlob();
}
var worker = new Worker(URL.createObjectURL(blob));
var results_store = {};
worker.onmessage=({data})=>{
results_store[data.id](data.data);
delete results_store[data.id];
}
return function (...args) {
var id = Array(64).fill(0).map(()=>Math.random().toString(36)).join("").replace("0.","").substr(0,64);
let p = new Promise((resolve,reject)=>{
worker.postMessage({id,data:args});
results_store[id]=(data)=>resolve(data);
});
return p;
}
}
let l = createOffloadedFunction(function(name){return "hi "+mangle(name);},function mangle(thing){return thing.split("").reverse().join("");});
l("Nitro").then(console.log)// -> hi ortiN
the perpose of this is to conver a non async function into a decenteralized async function using web workers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment