Skip to content

Commit

Permalink
Handle carriage returns properly
Browse files Browse the repository at this point in the history
  • Loading branch information
papb committed Oct 22, 2020
1 parent c21c19f commit 65cb099
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
8 changes: 7 additions & 1 deletion source/tsv2json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@ function extractFirstCell(tsvCharacters: NonemptyArray<string>): CellExtractionR

while (index < tsvCharacters.length) {
const char = tsvCharacters[index];
const nextChar = tsvCharacters[index + 1];

if (escapedMode) {
if (char === '"') {
if (tsvCharacters[index + 1] === '"') {
if (nextChar === '"') {
result.push('"');
index++;
} else {
Expand All @@ -37,6 +38,11 @@ function extractFirstCell(tsvCharacters: NonemptyArray<string>): CellExtractionR
result.push(char);
}
} else {
if (char === '\r' && nextChar === '\n') {
index++;
return done(true);
}

if (char === '\n') return done(true);
if (char === '\t') return done(false);
result.push(char);
Expand Down
3 changes: 3 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ test('tsv2json', t => {
const complexJsonWithPreparedEmptyRow = complexJson.map(x => x.length === 0 ? [''] : x);
t.deepEqual(tsv2json(complexFullyQuotedTsv), complexJsonWithPreparedEmptyRow);
t.deepEqual(tsv2json(complexQuotedAsNeededTsv), complexJsonWithPreparedEmptyRow);

t.deepEqual(tsv2json('"aa\r\nbb"'), [['aa\r\nbb']]);
t.deepEqual(tsv2json('aa\r\nbb'), [['aa'], ['bb']]);
});

test('tsv2json throws on invalid input', t => {
Expand Down

0 comments on commit 65cb099

Please sign in to comment.