Last active
May 4, 2018 18:19
-
-
Save mootari/9056e95c24a3ab925f17aa283a20326c to your computer and use it in GitHub Desktop.
Inlining objects in Javascript.
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
// Recursively inlines Function, RegExp and undefined. | |
function serialize(value) { | |
const type = typeof value; | |
const json = JSON.stringify; | |
if(type === 'function') { | |
return value.toString(); | |
} | |
if(type === 'object') { | |
if(value === null) { | |
return json(value); | |
} | |
if(value instanceof RegExp) { | |
return value.toString(); | |
} | |
if(Array.isArray(value)) { | |
return '[' + value.map(serialize).join(',') + ']'; | |
} | |
const body = Object.keys(value).map(name => json(name) + ':' + serialize(value[name])); | |
return '{' + body.join(',') + '}'; | |
} | |
if(type === 'undefined') { | |
return type; | |
} | |
return json(value); | |
} |
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 createWorker(data, onInit) { | |
const script = ` | |
'use strict'; | |
const data = ${serialize(data)}; | |
(${onInit.toString()}).call(this, self, data); | |
`; | |
const blob = new Blob([script], {type: 'text/javascript'}); | |
const worker = new Worker(URL.createObjectURL(blob)); | |
return worker; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment