Skip to content

Instantly share code, notes, and snippets.

@uchcode
Last active February 15, 2019 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uchcode/89c2f1e2848e8309ff73a963451ef6f6 to your computer and use it in GitHub Desktop.
Save uchcode/89c2f1e2848e8309ff73a963451ef6f6 to your computer and use it in GitHub Desktop.
JSOA: JSON Array
/*
"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