Skip to content

Instantly share code, notes, and snippets.

@mootari
Last active May 4, 2018 18:19
Show Gist options
  • Save mootari/9056e95c24a3ab925f17aa283a20326c to your computer and use it in GitHub Desktop.
Save mootari/9056e95c24a3ab925f17aa283a20326c to your computer and use it in GitHub Desktop.
Inlining objects in Javascript.
// 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);
}
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