Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/matrix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ describe("Matrix.split()", () => {
expect(Matrix.split(CSV, Number)).toEqual(EXAMPLE_MATRIX);
});

const CSVWithTrailingNewline = `${CSV}\n`;
test("Constructs a matrix from a CSV string with trailing newline", () => {
expect(Matrix.split(CSVWithTrailingNewline, Number)).toEqual(
EXAMPLE_MATRIX
);
});

test("Keeps line breaks inside double quotes", () => {
const csv = '"Value\n1"\tValue2\t"Value\n3"';
const result = Matrix.split(csv, (value) => value);
Expand Down
27 changes: 19 additions & 8 deletions src/matrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,18 +167,29 @@ export function split<T>(
horizontalSeparator = "\t",
verticalSeparator: string | RegExp = /\r\n|\n|\r/
): Matrix<T> {
const verticalSeparatorRegExp =
typeof verticalSeparator === "string"
? new RegExp(verticalSeparator)
: verticalSeparator;

// Temporarily replace line breaks inside quotes
const replaced = csv.replace(/"([^"]*?)"/g, (match, p1) => {
return p1.replace(/\n/g, "\\n");
});
return replaced.split(verticalSeparator).map((row) =>
row
.split(horizontalSeparator)
.map((line) => {
// Restore original line breaks in each line
return line.replace(/\\n/g, "\n");
})
.map(transform)
return (
replaced
// delete trailing new line character
.replace(new RegExp(`(${verticalSeparatorRegExp.source})$`), "")
.split(verticalSeparatorRegExp)
.map((row) =>
row
.split(horizontalSeparator)
.map((line) => {
// Restore original line breaks in each line
return line.replace(/\\n/g, "\n");
})
.map(transform)
)
);
}

Expand Down