Last active
February 15, 2019 16:46
-
-
Save uchcode/89c2f1e2848e8309ff73a963451ef6f6 to your computer and use it in GitHub Desktop.
JSOA: JSON Array
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
/* | |
"background-color:red;font-size:32px;" | |
{backgroundColor:"red",fontSize:"32px"} | |
[{backgroundColor:"red"},{fontSize:"32px"}] | |
[["background-color","red"],["font-size","32px"]] | |
*/ | |
const kebab_case = s => s.replace(/[A-Z]/g,"-$&").toLowerCase(); | |
const camel_case = s => s.replace(/(\-)([a-z])/g,(...a)=>a[2].toUpperCase()); | |
const assign = (a,b) => Object.assign(a,b); | |
const JSOA = {}; | |
// string -> object | |
JSOA.parse = s => s?JSOA.parseSplit(s).reduce(assign,{}):{}; | |
// string -> object array | |
JSOA.parseSplit = s => s?s.split(';').map(e=>e.trim()).filter(e=>e).map(e=>e.split(':').reduce((a,b)=>({[camel_case(a.trim())]:b.trim()}))):[]; | |
// string -> array array | |
JSOA.splitSplit = s => s?JSOA.entries(JSOA.parse(s)):[]; | |
// object -> string | |
JSOA.stringify = o => o?Object.entries(o).map(([k,v])=>`${kebab_case(k)}:${v};`).join(''):''; | |
// object -> object array | |
JSOA.arrange = o => o?Object.entries(o).map(([k,v])=>({[k]:v})):[]; | |
// object -> array array | |
JSOA.entries = o => o?Object.entries(o).map(([k,v])=>([kebab_case(k),v])):[]; | |
// object array -> string | |
JSOA.objectJoin = a => a?JSOA.stringify(JSOA.objectMerge(a)):''; | |
// object array -> object | |
JSOA.objectMerge = a => a?a.reduce(assign,{}):{}; | |
// object array -> array array | |
JSOA.objectConvert = a => a?JSOA.entries(JSOA.objectMerge(a)):[]; | |
// array array -> string | |
JSOA.arrayJoin = a => a?JSOA.stringify(JSOA.arrayMerge(a)):''; | |
// array array -> object | |
JSOA.arrayMerge = a => a?a.map(([k,v])=>({[camel_case(k)]:v})).reduce(assign,{}):{}; | |
// array array -> object array | |
JSOA.arrayConvert = a => a?JSOA.arrange(JSOA.arrayMerge(a)):[]; | |
export default JSOA; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment