Skip to content

Instantly share code, notes, and snippets.

@HenrikJoreteg
Created January 26, 2017 05:34
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 HenrikJoreteg/34ea5b785b68b1bf58cab183a68753ed to your computer and use it in GitHub Desktop.
Save HenrikJoreteg/34ea5b785b68b1bf58cab183a68753ed to your computer and use it in GitHub Desktop.
serializable functions for running code in unknown context on the main thread
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