uchcode
2/15/2019 - 6:32 AM

JSOA: JSON Array

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;