💫 still working

This commit is contained in:
abdennour 2016-11-25 16:48:16 +03:00
commit 05a02765d0
2 changed files with 39 additions and 16 deletions

View file

@ -1,26 +1,47 @@
const isJsons = (array) => array.every(row => (typeof row === 'object' && !(row instanceof Array)))
const isArrays = (array) => array.every(row => Array.isArray(row))
export const isJsons = ((array) => array.every(
row => (typeof row === 'object' && !(row instanceof Array))
));
const jsonsHeaders = (array) => Array.from(
export const isArrays = ((array) => array.every(
row => Array.isArray(row)
));
export const jsonsHeaders = ((array) => Array.from(
array.map(json => Object.keys(json))
.reduce((a, b) => new Set([...a, ...b]), [])
);
const jsons2arrays = (jsons, headers) => {
));
export const jsons2arrays = (jsons, headers) => {
headers = headers || jsonsHeaders(jsons);
return [headers, ...array.map((object) =>
headers.map((header) =>
object[header] ? object[header] : ''))]
};
const joiner = (data) => data.map((row, index) => row.join(',')).join(`\n`);
const arrays2csv = (data, headers) => joiner(headers ? [headers, ...data] : data);
const jsons2csv = (data, headers) => joiner(jsons2arrays(data, headers))
const toCSV = (data, headers) => {
if(isJsons(data)) return jsons2csv(data, headers);
if(isArrays(data)) return jsons2csv(data, headers);
throw new TypeError(`Data should be an array of arrays OR array of objects `);
};
export const buildURI = (data, headers) => encodeURI(
`data:text/csv;charset=utf-8,${toCSV(data, headers)}`
export const joiner = ((data) =>
data.map((row, index) => row.join(',')).join(`\n`)
);
export const arrays2csv = ((data, headers) =>
joiner(headers ? [headers, ...data] : data)
);
export const jsons2csv = ((data, headers) =>
joiner(jsons2arrays(data, headers))
);
export const string2csv = ((data, headers) =>
(headers) ? `${headers.join(`,`)}\n${data}`: data
)
export const toCSV = (data, headers) => {
if (isJsons(data)) return jsons2csv(data, headers);
if (isArrays(data)) return arrays2csv(data, headers);
if (typeof data ==='string') return string2csv(data, headers);
throw new TypeError(`Data should be a "String", "Array of arrays" OR "Array of objects" `);
};
export const buildURI = ((data, headers) => encodeURI(
`data:text/csv;charset=utf-8,${toCSV(data, headers)}`
)
);