Skip to content

Instantly share code, notes, and snippets.

@izelnakri
Last active November 1, 2017 11:11
Show Gist options
  • Select an option

  • Save izelnakri/045bb93a339e01456d54fa33c8a18946 to your computer and use it in GitHub Desktop.

Select an option

Save izelnakri/045bb93a339e01456d54fa33c8a18946 to your computer and use it in GitHub Desktop.
Turn JS data to JS string of code.
export default JSValueToCode;
function JSObjectToCode(object) {
if (Array.isArray(object)) {
return '[' + object.map((element) => JSValueToCode(element)).join(', ') + ']';
}
return '{' + Object.keys(object).reduce((result, key) => {
const codeValue = JSValueToCode(object[key]);
const pair = `'${key}': ${codeValue}`;
return result === '' ? pair : [result, pair].join(', ');
}, '') + '}';
}
function JSValueToCode(value) {
const valueType = typeof value;
if (valueType === 'undefined') {
return 'undefined';
} else if (value === null) {
return 'null';
} else if (valueType === 'number' || valueType === 'boolean') {
return `${value}` ;
} else if (valueType === 'string') {
return `'${value}'`;
} else if (valueType === 'function') {
return value.toString();
}
return JSObjectToCode(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment