rewrite parseData.js for general purpose
This commit is contained in:
parent
05423fb8ff
commit
80f0b170d8
2 changed files with 36 additions and 31 deletions
36
src/renderer/util/parseData.js
Normal file
36
src/renderer/util/parseData.js
Normal file
|
@ -0,0 +1,36 @@
|
|||
|
||||
const parseJson = data => JSON.stringify(data);
|
||||
|
||||
// No need for an external module:
|
||||
// https://gist.github.com/btzr-io/55c3450ea3d709fc57540e762899fb85
|
||||
const parseCsv = data => {
|
||||
// Get items for header
|
||||
const getHeaders = temp =>
|
||||
Object.entries(temp)
|
||||
.map(([key]) => key)
|
||||
.join(',');
|
||||
// Get rows content
|
||||
const getData = list =>
|
||||
list
|
||||
.map(item => {
|
||||
const row = Object.entries(item)
|
||||
.map(([key, value]) => value)
|
||||
.join(',');
|
||||
return row;
|
||||
})
|
||||
.join('\n');
|
||||
// Return CSV string
|
||||
return `${getHeaders(data[0])} \n ${getData(data)}`;
|
||||
};
|
||||
|
||||
export function parseData(data, format) {
|
||||
// Check for validation
|
||||
const valid = (data && data[0]) && format;
|
||||
// Pick a format
|
||||
const formats = {
|
||||
csv: list => parseCsv(list),
|
||||
json: list => parseJson(list),
|
||||
};
|
||||
// Return parsed data: JSON || CSV
|
||||
return valid && formats[format] ? formats[format](data) : undefined;
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
function parseJson(data) {
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
|
||||
function parseCsv(data) {
|
||||
// Get items for header
|
||||
const getHeaders = temp =>
|
||||
Object.entries(temp)
|
||||
.map(([key]) => key)
|
||||
.join(',');
|
||||
// Get rows content
|
||||
const getData = list =>
|
||||
list
|
||||
.map(item => {
|
||||
const row = Object.entries(item)
|
||||
.map(([key, value]) => value)
|
||||
.join(',');
|
||||
return row;
|
||||
})
|
||||
.join('\n');
|
||||
// Return CSV string
|
||||
return `${getHeaders(data[0])} \n ${getData(data)}`;
|
||||
}
|
||||
|
||||
export function parseTransactions(transactions, format) {
|
||||
const formats = {
|
||||
csv: data => parseCsv(data),
|
||||
json: data => parseJson(data),
|
||||
};
|
||||
return formats[format] ? formats[format](transactions) : undefined;
|
||||
}
|
Loading…
Add table
Reference in a new issue