Here I am figuring out how I could add an extra row after the last item of each group or after the item that has true for 'isLastItem's value.
Here's the original source:
fileControllers.ts
const item1 = [
{route: LA-HK, fare: 3000, groupNo: 1, isLastItem: false},
{route: HK-LA, fare: 2980, groupNo: 1, isLastItem: true},
{route: LDN-BKK, fare: 2700, groupNo: 2, isLastItem: true},
{route: SGN-HCM, fare: 2300, groupNo: 3, isLastItem: false},
{route: HCM-SGN, fare: 2400, groupNo: 3, isLastItem: true}
]
const item2 = [
{route: DF-EK, fare: 2342, groupNo: 4, isLastItem: false},
{route:EK-DF, fare: 2354, groupNo: 4, isLastItem: true},
]
const item3 = [
{route: PO-KL, fare: 3495, groupNo: 5, isLastItem: false},
{route: KL-PO, fare: 2354, groupNo: 5, isLastItem: true},
{route: DS-RU, fare: 2300, groupNo: 6, isLastItem: false},
{route: RU-DS, fare: 2400, groupNo: 6, isLastItem: true}
]
const csvData1 = item1.map(createBillInfoForCsv)
const csvData2 = item2.map(createBillInfoForCsv)
const csvData3 = item3.map(createBillInfoForCsv)
const createBillInfoForCsv = (createBillInfoForCsv: TRow): TBillFile => ({
'Travel Route': createBillInfoForCsv.route,
'Total Fare': createBillInfoForCsv.taxedFare.toString(),
});
return converToCSVBill(csvData1, csvData2, csvData3, 'Shift_JIS', BillFileHeader, title, summary.join(''));
csv/index.ts (json2csv is used here)
const converToCSVBill = <T>(
data: T[],
data2: T[],
data3: T[],
charset: TCharset,
fields: string[],
titleForCsv?: string,
summary?: string,
): Buffer => {
const SEPARATOR = '\r\n';
const title = titleForCsv ? titleForCsv + SEPARATOR.repeat(2) : '';
const csv1 = parse(data, { eol: SEPARATOR, fields: fields });
let csv2 = '';
let csv3 = '';
if (data2.length) {
csv2 = parse(data2, { eol: SEPARATOR, header: false});
}
if (data3.length) {
csv3 = parse(data3, { eol: SEPARATOR, header: false });
}
return encode(title + (summary ?? '') + csv1 + csv2 + csv3, charset);
};
Here's the expected output:
I tried to modified createBillInfoForCsv by adding the delimiter '\r\n' after the last item, 'Total Fare', but it ended up only adding a line break within a cell.
I figure out that it better to do modification during parse when array objects turn into a string, but I think it's better not to modified the library directly.
Therefore, I would appreciate if anyone could show me how I can create the expected output.
Thank you.
