Last active
May 12, 2023 14:59
-
-
Save gera2ld/bc69240c820c8fccee9911fc047c7002 to your computer and use it in GitHub Desktop.
CSV parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function parseCsv(input: string, delimiter = ',') { | |
const scanQuoteEnd = (i: number) => { | |
for (; i < input.length; i += 1) { | |
const c = input[i]; | |
if (c === '"') { | |
if (input[i + 1] === '"') i += 1; | |
else break; | |
} | |
} | |
if (!input[i]) throw new Error('Quote is expected'); | |
return i; | |
}; | |
const scanDelimiter = (i: number) => { | |
for (; i < input.length; i += 1) { | |
const c = input[i]; | |
if ([delimiter, '\n'].includes(c)) { | |
break; | |
} | |
} | |
return i; | |
}; | |
const rows: string[][] = []; | |
let row: string[] = []; | |
for (let i = 0; i < input.length; i += 1) { | |
if (input[i] === '"') { | |
const j = scanQuoteEnd(i + 1); | |
const item = input.slice(i + 1, j).replace(/""/g, '"'); | |
row.push(item); | |
i = scanDelimiter(j + 1); | |
if (i !== j + 1) throw new Error('Unexpected token'); | |
} else { | |
const j = scanDelimiter(i); | |
const item = input.slice(i, j); | |
row.push(item); | |
i = j; | |
} | |
if (input[i] !== delimiter) { | |
rows.push(row); | |
row = []; | |
} | |
} | |
if (row.length) rows.push(row); | |
return rows; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment