Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(csv): infer column names from object arrays for stringify() #6122

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
29 changes: 25 additions & 4 deletions csv/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ export type StringifyOptions = {
* column of output. This is also where you can provide an explicit header
* name for the column.
*
* @default {[]}
* @default {undefined}
*/
columns?: readonly Column[];
columns?: readonly Column[] | undefined;
/**
* Whether to add a
* {@link https://en.wikipedia.org/wiki/Byte_order_mark | byte-order mark} to the
Expand Down Expand Up @@ -429,7 +429,7 @@ export function stringify(
data: readonly DataItem[],
options?: StringifyOptions,
): string {
const { headers = true, separator: sep = ",", columns = [], bom = false } =
const { headers = true, separator: sep = ",", columns, bom = false } =
options ?? {};

if (sep.includes(QUOTE) || sep.includes(CRLF)) {
Expand All @@ -441,7 +441,12 @@ export function stringify(
throw new TypeError(message);
}

const normalizedColumns = columns.map(normalizeColumn);
if (columns && !Array.isArray(columns)) {
throw new TypeError("Invalid type: columns can only be an array.");
}

const definedColumns = columns ?? inferColumns(data);
const normalizedColumns = definedColumns.map(normalizeColumn);
let output = "";

if (bom) {
Expand All @@ -465,3 +470,19 @@ export function stringify(

return output;
}

/**
* Infers the columns from the first object element of the given array.
*/
function inferColumns(data: readonly DataItem[]) {
const firstElement = data.at(0);
if (
firstElement &&
typeof firstElement === "object" &&
!Array.isArray(firstElement)
) {
return Object.keys(firstElement);
}

return [];
}
2 changes: 1 addition & 1 deletion csv/stringify_stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class CsvStringifyStream<TOptions extends CsvStringifyStreamOptions>
* @param options Options for the stream.
*/
constructor(options?: TOptions) {
const { separator, columns = [] } = options ?? {};
const { separator, columns } = options ?? {};

super(
{
Expand Down
12 changes: 7 additions & 5 deletions csv/stringify_stream_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Deno.test({
await assertRejects(
async () => await Array.fromAsync(readable),
TypeError,
"No property accessor function was provided for object",
"Invalid type: columns can only be an array.",
);
});

Expand All @@ -90,10 +90,12 @@ Deno.test({
{ id: 3, name: "baz" },
// @ts-expect-error `columns` option is required
]).pipeThrough(new CsvStringifyStream());
await assertRejects(
async () => await Array.fromAsync(readable),
TypeError,
);
const output = await Array.fromAsync(readable);
assertEquals(output, [
"1,foo\r\n",
"2,bar\r\n",
"3,baz\r\n",
]);
});
},
});
48 changes: 21 additions & 27 deletions csv/stringify_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,33 +72,6 @@ Deno.test({
},
},
);

await t.step(
{
name: "Invalid data, no columns",
fn() {
const data = [{ a: 1 }, { a: 2 }];
assertThrows(
() => stringify(data),
TypeError,
"No property accessor function was provided for object",
);
},
},
);
await t.step(
Comment on lines -76 to -89
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like these were duplicates, removed both as they are not relevant anymore

{
name: "Invalid data, no columns",
fn() {
const data = [{ a: 1 }, { a: 2 }];
assertThrows(
() => stringify(data),
TypeError,
"No property accessor function was provided for object",
);
},
},
);
await t.step(
{
name: "No data, no columns",
Expand Down Expand Up @@ -591,5 +564,26 @@ Deno.test({
});
},
});
await t.step(
{
name: "Object array with no columns, should infer columns",
fn() {
const data = [{ a: 1 }, { a: 2 }, { b: 3 }];
const output = `a${CRLF}1${CRLF}2${CRLF}${CRLF}`;
assertEquals(stringify(data), output);
},
},
);
await t.step(
{
name: "Object array with columns, shouldn't infer columns",
fn() {
const data = [{ a: 1 }, { a: 2 }, { b: 3 }];
const columns = ["a"];
const output = `a${CRLF}1${CRLF}2${CRLF}${CRLF}`;
assertEquals(stringify(data, { columns }), output);
},
},
);
},
});
Loading