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

BREAKING(encoding/csv): add return type to csv's parse and remove a parse func from args #1724

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
57 changes: 7 additions & 50 deletions encoding/csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,20 +334,12 @@ export async function readMatrix(
* Parse the CSV string/buffer with the options provided.
*
* ColumnOptions provides the column definition
* and the parse function for each entry of the
* column.
*/
export interface ColumnOptions {
/**
* Name of the column to be used as property
*/
name: string;
/**
* Parse function for the column.
* This is executed on each entry of the header.
* This can be combined with the Parse function of the rows.
*/
parse?: (input: string) => unknown;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I may be reading too much into the comment thread in #881. To keep the logic consistent I removed the parse function from columns as well. Should this be done?

Now, if the parse is removed from column options maybe the function signature for columns?: string[] | ColumnOptions[] should just be simplified to columns?: string[] as below will evaluate to the same.

parse(data, { columns: ['a', 'b', 'c']});

parse(data, { columns: [{ name: 'a' }, { name: 'b' }, { name: 'c' } ] });

Copy link
Member

Choose a reason for hiding this comment

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

I'm in favor of removing this

}

export interface ParseOptions extends ReadOptions {
Expand All @@ -361,44 +353,22 @@ export interface ParseOptions extends ReadOptions {
* If you provide `string[]` or `ColumnOptions[]`, those names will be used for header definition.
*/
columns?: string[] | ColumnOptions[];

/** Parse function for rows.
* Example:
* ```ts
* import { parse } from "./csv.ts";
* const r = await parse('a,b,c\ne,f,g\n', {
* columns: ["this", "is", "sparta"],
* parse: (_e: unknown) => {
* const e = _e as { this: unknown, is: unknown, sparta: unknown };
* return { super: e.this, street: e.is, fighter: e.sparta };
* }
* });
* // output
* // [
* // { super: "a", street: "b", fighter: "c" },
* // { super: "e", street: "f", fighter: "g" }
* // ]
* ```
*/
parse?: (input: unknown) => unknown;
}

/**
* Csv parse helper to manipulate data.
* Provides an auto/custom mapper for columns and parse function
* for columns and rows.
* Provides an auto/custom mapper for columns.
* @param input Input to parse. Can be a string or BufReader.
* @param opt options of the parser.
* @returns If you don't provide `opt.skipFirstRow`, `opt.parse`, and `opt.columns`, it returns `string[][]`.
* If you provide `opt.skipFirstRow` or `opt.columns` but not `opt.parse`, it returns `object[]`.
* If you provide `opt.parse`, it returns an array where each element is the value returned from `opt.parse`.
* @returns If you don't provide `opt.skipFirstRow` and `opt.columns`, it returns `string[][]`.
* If you provide `opt.skipFirstRow` or `opt.columns`, it returns `Record<string, unkown>[]`.
*/
export async function parse(
input: string | BufReader,
opt: ParseOptions = {
skipFirstRow: false,
},
): Promise<unknown[]> {
): Promise<string[][] | Record<string, unknown>[]> {
Copy link
Member

Choose a reason for hiding this comment

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

I think if we do overloading like the below, it would be able to return more correct type depending of the options:

export async function parse(
  input: string | BufReader
): Promise<string[][]>;
export async function parse(
  input: string | BufReader,
  opt: Omit<ParseOptions, "columns" | "skipFirstRow">,
): Promise<string[][]>;
export async function parse(
  input: string | BufReader,
  opt: Omit<ParseOptions, "columns"> & {
    columns: string[] | ColumnOptions[],
  },
): Promise<Record<string, unknown>[]>;
export async function parse(
  input: string | BufReader,
  opt: Omit<ParseOptions, "skipFirstRow"> & {
    skipFirstRow: true,
  },
): Promise<Record<string, unknown>[]>;
export async function parse(
  input: string | BufReader,
  opt: ParseOptions = {
    skipFirstRow: false,
  },
): Promise<string[][] | Record<string, unknown>[]> { ... }

let r: string[][];
if (input instanceof BufReader) {
r = await readMatrix(input, opt);
Expand Down Expand Up @@ -436,31 +406,18 @@ export async function parse(
);
}
}
return r.map((e): unknown => {

return r.map((e) => {
if (e.length !== headers.length) {
throw `Error number of fields line:${i}`;
}
i++;
const out: Record<string, unknown> = {};
for (let j = 0; j < e.length; j++) {
const h = headers[j];
if (h.parse) {
out[h.name] = h.parse(e[j]);
} else {
out[h.name] = e[j];
}
}
if (opt.parse) {
return opt.parse(out);
out[headers[j].name] = e[j];
}
return out;
});
}
if (opt.parse) {
return r.map((e: string[]): unknown => {
assert(opt.parse, "opt.parse must be set");
return opt.parse(e);
});
}
return r;
}
59 changes: 3 additions & 56 deletions encoding/csv_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,70 +549,18 @@ const parseTestCases = [
{ this: "e", is: "f", sparta: "g" },
],
},
{
name: "header mapping parse entry",
in: "a,b,c\ne,f,g\n",
columns: [
{
name: "this",
parse: (e: string): string => {
return `b${e}$$`;
},
},
{
name: "is",
parse: (e: string): number => {
return e.length;
},
},
{
name: "sparta",
parse: (e: string): unknown => {
return { bim: `boom-${e}` };
},
},
],
result: [
{ this: "ba$$", is: 1, sparta: { bim: `boom-c` } },
{ this: "be$$", is: 1, sparta: { bim: `boom-g` } },
],
},
{
name: "multiline parse",
in: "a,b,c\ne,f,g\n",
parse: (e: string[]): unknown => {
return { super: e[0], street: e[1], fighter: e[2] };
},
skipFirstRow: false,
result: [
{ super: "a", street: "b", fighter: "c" },
{ super: "e", street: "f", fighter: "g" },
],
},
{
name: "header mapping object parseline",
in: "a,b,c\ne,f,g\n",
columns: [{ name: "this" }, { name: "is" }, { name: "sparta" }],
parse: (e: Record<string, unknown>): unknown => {
return { super: e.this, street: e.is, fighter: e.sparta };
},
result: [
{ super: "a", street: "b", fighter: "c" },
{ super: "e", street: "f", fighter: "g" },
],
},
{
name: "provides both opts.skipFirstRow and opts.columns",
in: "a,b,1\nc,d,2\ne,f,3",
skipFirstRow: true,
columns: [
{ name: "foo" },
{ name: "bar" },
{ name: "baz", parse: (e: string) => Number(e) },
{ name: "baz" },
],
result: [
{ foo: "c", bar: "d", baz: 2 },
{ foo: "e", bar: "f", baz: 3 },
{ foo: "c", bar: "d", baz: "2" },
{ foo: "e", bar: "f", baz: "3" },
],
},
];
Expand All @@ -624,7 +572,6 @@ for (const testCase of parseTestCases) {
const r = await parse(testCase.in, {
skipFirstRow: testCase.skipFirstRow,
columns: testCase.columns,
parse: testCase.parse as (input: unknown) => unknown,
});
assertEquals(r, testCase.result);
},
Expand Down