Created
January 26, 2017 05:34
-
-
Save HenrikJoreteg/34ea5b785b68b1bf58cab183a68753ed to your computer and use it in GitHub Desktop.
serializable functions for running code in unknown context on the main thread
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
export default (fn, ...args) => { | |
if (typeof window !== 'undefined') { | |
fn(...args) | |
} else { | |
const last = args.slice(-1)[0] | |
let argString = '' | |
if (typeof last !== 'undefined') { | |
argString = args.reduce((accum, val, index) => { | |
const type = typeof val | |
const isLast = index === args.length - 1 | |
const isFunction = type === 'function' | |
if (isFunction) { | |
if (isLast) { | |
const id = Math.random().toString() | |
accum.push(`function(err,payload){worker.postMessage({type:'callback',cbId:'${id}',error:err,payload:payload})}`) | |
self[id] = (data) => val(data.error, data.payload) | |
} else { | |
accum.push(val.toString()) | |
} | |
} else { | |
accum.push(JSON.stringify(val)) | |
} | |
return accum | |
}, []).join(',') | |
} | |
const serializedFn = fn.toString() | |
self.postMessage(`return (${serializedFn})(${argString})`) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment