Skip to content

Instantly share code, notes, and snippets.

@JennieJi
Last active December 13, 2020 03:04
Show Gist options
  • Save JennieJi/7115327714a3c125fab04f02de631077 to your computer and use it in GitHub Desktop.
Save JennieJi/7115327714a3c125fab04f02de631077 to your computer and use it in GitHub Desktop.
Simple csv to array demo
const COLUMN_DELIMITER = ',';
export function csvToArray(csv: string): string[][] {
const table = [] as string[][];
let row = [];
let cell = '';
let openQuote = false;
let i = 0;
const pushCell = () => {
row.push(cell);
cell = '';
};
const pushRow = () => {
pushCell();
table.push(row);
row = [];
}
const handleSeparator = (i: number) => {
const c = csv.charAt(i);
if (c === COLUMN_DELIMITER) {
pushCell();
} else if (c === '\r') {
if (csv.charAt(i + 1) === '\n') {
i++;
}
pushRow();
} else if (c === '\n') {
pushRow();
} else {
return false;
}
return true;
}
while (i < csv.length) {
const c = csv.charAt(i);
const next = csv.charAt(i + 1);
if (!openQuote && !cell && c === '"') {
openQuote = true;
} else if (openQuote) {
if (c !== '"') {
cell += c;
} else if (next === '"') {
cell += c;
i++;
} else {
openQuote = false
if (!handleSeparator(++i)){
throw new Error('Wrong CSV format!');
}
}
} else if (!handleSeparator(i)) {
cell += c;
}
i++;
}
if (cell) {
pushRow();
}
return table;
}
console.log(csvToArray('1",2,3'));
console.log(csvToArray('"1",2,3'));
console.log(csvToArray('"1""",2,3'));
console.log(csvToArray(`"1",2,3
4,5`));
console.log(csvToArray(`"1""
",2,3
4,5`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment