Skip to content

Commit

Permalink
refactor(csv): remove dead code and improve tests (#5151)
Browse files Browse the repository at this point in the history
  • Loading branch information
kt3k committed Jun 26, 2024
1 parent 2fd7c33 commit ba256e3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 26 deletions.
46 changes: 20 additions & 26 deletions csv/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,35 +50,29 @@ class Parser {
#readLine(): string | null {
if (this.#isEOF()) return null;

if (
!this.#input.startsWith("\r\n", this.#cursor) ||
!this.#input.startsWith("\n", this.#cursor)
) {
let buffer = "";
let hadNewline = false;
while (this.#cursor < this.#input.length) {
if (this.#input.startsWith("\r\n", this.#cursor)) {
hadNewline = true;
this.#cursor += 2;
break;
}
if (
this.#input.startsWith("\n", this.#cursor)
) {
hadNewline = true;
this.#cursor += 1;
break;
}
buffer += this.#input[this.#cursor];
this.#cursor += 1;
let buffer = "";
let hadNewline = false;
while (this.#cursor < this.#input.length) {
if (this.#input.startsWith("\r\n", this.#cursor)) {
hadNewline = true;
this.#cursor += 2;
break;
}
if (!hadNewline && buffer.endsWith("\r")) {
buffer = buffer.slice(0, -1);
if (
this.#input.startsWith("\n", this.#cursor)
) {
hadNewline = true;
this.#cursor += 1;
break;
}

return buffer;
buffer += this.#input[this.#cursor];
this.#cursor += 1;
}
return null;
if (!hadNewline && buffer.endsWith("\r")) {
buffer = buffer.slice(0, -1);
}

return buffer;
}
#isEOF(): boolean {
return this.#cursor >= this.#input.length;
Expand Down
18 changes: 18 additions & 0 deletions csv/parse_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,24 @@ Deno.test({
assertEquals(parse(input, { trimLeadingSpace: true }), output);
},
});
await t.step({
name: "leading line breaks",
fn() {
const input = "\n\na,b,c";
const output = [["a", "b", "c"]];
assertEquals(parse(input), output);
},
});
await t.step({
name: "throws when skipFirstRow=true with empty data",
fn() {
assertThrows(
() => parse("", { skipFirstRow: true }),
Error,
"Headers must be defined",
);
},
});
},
});

Expand Down

0 comments on commit ba256e3

Please sign in to comment.