lbry-desktop/ui/util/parse-data.js

62 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-03-22 16:43:35 +01:00
// JSON parser
const parseJson = (data, filters = []) => {
const list = data.map(item => {
const temp = {};
// Apply filters
Object.entries(item).forEach(([key, value]) => {
if (!filters.includes(key)) temp[key] = value;
});
return temp;
});
// Beautify JSON
return JSON.stringify(list, null, '\t');
};
2018-03-22 16:43:35 +01:00
// CSV Parser
// No need for an external module:
// https://gist.github.com/btzr-io/55c3450ea3d709fc57540e762899fb85
2018-03-22 16:43:35 +01:00
const parseCsv = (data, filters = []) => {
// Get items for header
2018-03-22 16:43:35 +01:00
const getHeaders = item => {
const list = [];
// Apply filters
Object.entries(item).forEach(([key]) => {
if (!filters.includes(key)) list.push(key);
});
// return headers
return list.join(',');
};
// Get rows content
const getData = list =>
list
.map(item => {
2018-03-22 16:43:35 +01:00
const row = [];
// Apply filters
Object.entries(item).forEach(([key, value]) => {
if (!filters.includes(key)) row.push(value);
});
// return rows
return row.join(',');
})
.join('\n');
2018-03-22 16:43:35 +01:00
// Return CSV string
return `${getHeaders(data[0])} \n ${getData(data)}`;
};
2018-03-22 16:43:35 +01:00
const parseData = (data, format, filters = []) => {
// Check for validation
2018-02-24 01:24:00 +01:00
const valid = data && data[0] && format;
// Pick a format
const formats = {
2018-03-22 16:43:35 +01:00
csv: list => parseCsv(list, filters),
json: list => parseJson(list, filters),
};
2018-03-22 16:43:35 +01:00
// Return parsed data: JSON || CSV
return valid && formats[format] ? formats[format](data) : undefined;
2018-02-24 01:24:00 +01:00
};
export default parseData;