Last active
November 1, 2017 11:11
-
-
Save izelnakri/045bb93a339e01456d54fa33c8a18946 to your computer and use it in GitHub Desktop.
Turn JS data to JS string of code.
This file contains hidden or 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 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