Last active
October 30, 2018 12:44
-
-
Save highercomve/4fc98caf3bbdcfd8e9e22422a8f282fe to your computer and use it in GitHub Desktop.
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
| import _chain from 'pipeable' | |
| function WorkerWrapper () { | |
| var poster = function (data) { | |
| importScripts(data.funcFileUrl) | |
| data.params.length = Object.keys(data.params).length | |
| postMessage(workerCallBack.apply(null, Array.from(data.params))) | |
| } | |
| onmessage = function (e) { | |
| poster(e.data) | |
| } | |
| } | |
| function FuncToString (code) { | |
| return _chain(code.toString()) | |
| .pipe(function (workerString) { | |
| var code = `var __code = ${workerString}; __code();` | |
| return code | |
| }) | |
| .result() | |
| } | |
| function FuncToBlobUrl (funcString) { | |
| return _chain(funcString) | |
| .pipe(function (code) { | |
| return new Blob([code]) | |
| }) | |
| .pipe(window.URL.createObjectURL) | |
| .result() | |
| } | |
| function WorkerFactory (actorCode) { | |
| var worker = _chain(WorkerWrapper) | |
| .pipe(FuncToString) | |
| .pipe(FuncToBlobUrl) | |
| .pipe(function (blobUrl) { | |
| console.info('Creating new Worker') | |
| return new Worker(blobUrl) | |
| }) | |
| .result() | |
| var actorCode = `var workerCallBack = ${actorCode.toString()}` | |
| return function (params) { | |
| worker.postMessage({ | |
| funcFileUrl: FuncToBlobUrl(actorCode), | |
| params: arguments | |
| }) | |
| return new Promise((resolve, reject) => { | |
| worker.onmessage = e => { | |
| worker.terminate() | |
| resolve(e.data) | |
| } | |
| worker.onerror = e => { | |
| worker.terminate() | |
| reject(e) | |
| } | |
| }) | |
| } | |
| } | |
| export default WorkerFactory |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment