Created
April 11, 2019 17:42
-
-
Save teak1/66e8887a373f2a9eee6eb90e47df3363 to your computer and use it in GitHub Desktop.
This file contains 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 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; | |
} | |
} |
This file contains 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
let l = createOffloadedFunction(function(name){return "hi "+mangle(name);},function mangle(thing){return thing.split("").reverse().join("");}); | |
l("Nitro").then(console.log)// -> hi ortiN |
This file contains 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
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