Skip to content

Instantly share code, notes, and snippets.

@gera2ld
Last active May 12, 2023 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gera2ld/bc69240c820c8fccee9911fc047c7002 to your computer and use it in GitHub Desktop.
Save gera2ld/bc69240c820c8fccee9911fc047c7002 to your computer and use it in GitHub Desktop.
CSV parser
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