Created
December 19, 2017 16:24
-
-
Save stefanbirkner/5252641db9f682baabd8c03e526ac5ff to your computer and use it in GitHub Desktop.
JavaScript - Object2YAML
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
function concat(firstText, secondText) { | |
return firstText + secondText; | |
} | |
function escape(key) { | |
if (key.match(/^[A-Za-z0-9\-\_]+$/)) | |
return key | |
else | |
return `"${key}"` | |
} | |
function yaml(object, indent) { | |
indent = indent || '' | |
return Object.keys(object) | |
.map( | |
key => { | |
if (typeof object[key] === 'string' || object[key] instanceof String) | |
return `${indent}${escape(key)}: ${object[key]}\n`; | |
else | |
return `${indent}${escape(key)}:\n` + yaml(object[key], indent + ' '); | |
} | |
) | |
.reduce(concat) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment