From a986e86019226e88b2199ca214aec4a44a83f95c Mon Sep 17 00:00:00 2001 From: Chesterkxng Date: Sun, 30 Mar 2025 13:03:55 +0000 Subject: [PATCH] feat: csv-to-tsv (service) --- src/pages/tools/csv/csv-to-tsv/service.ts | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/pages/tools/csv/csv-to-tsv/service.ts diff --git a/src/pages/tools/csv/csv-to-tsv/service.ts b/src/pages/tools/csv/csv-to-tsv/service.ts new file mode 100644 index 0000000..98ecaf0 --- /dev/null +++ b/src/pages/tools/csv/csv-to-tsv/service.ts @@ -0,0 +1,35 @@ +function unquoteIfQuoted(value: string, quoteCharacter: string): string { + if (value.startsWith(quoteCharacter) && value.endsWith(quoteCharacter)) { + return value.slice(1, -1); // Remove first and last character + } + return value; +} +export function csvToTsv( + input: string, + delimiter: string, + quoteCharacter: string, + commentCharacter: string, + header: boolean, + emptyLines: boolean +): string { + // edge case: if input is empty, return empty string + if (!input) return ''; + const lines = input.split('\n'); + // is header is set to false, remove the first line + if (!header) lines.shift(); + + const tsvLines = lines.map((line) => { + // if comment character is set, remove the lines that start with it + if (commentCharacter && line.startsWith(commentCharacter)) return ''; + const cells = line.split(delimiter); + cells.forEach((cell, index) => { + cells[index] = unquoteIfQuoted(cell, quoteCharacter); + }); + return cells.join('\t'); + }); + // if empty lines is set to true, remove the empty lines + + return !emptyLines + ? tsvLines.join('\n') + : tsvLines.filter((line) => line.trim() !== '').join('\n'); +}