From: Ardis Lu Date: Fri, 24 Jan 2025 04:21:43 +0000 (-0800) Subject: Add example to demonstrate passing a function to handleHeaders X-Git-Tag: v0.1.0~89 X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=bca50818f5df0403f167f0b57d35eb632f8130be;p=csvio Add example to demonstrate passing a function to handleHeaders --- diff --git a/examples/README.md b/examples/README.md index 118c703..6386a4c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -22,6 +22,8 @@ These examples demonstrate the most common, expected usage. [Example 1.4: Handling an irregularly-shaped CSV file](./ex1_4.js) +[Example 1.5: Duplicate input rows to the output](./ex1_5.js) + ### Section 2: Error strategies These examples demonstrate using the `onError` option to handle transformations that may throw errors. diff --git a/examples/data/ex1_5-in.csv b/examples/data/ex1_5-in.csv new file mode 100644 index 0000000..6347605 --- /dev/null +++ b/examples/data/ex1_5-in.csv @@ -0,0 +1,4 @@ +a,b,c +580,250,462 +325,950,740 +215,546,730 diff --git a/examples/data/ex1_5-out.csv b/examples/data/ex1_5-out.csv new file mode 100644 index 0000000..4126884 --- /dev/null +++ b/examples/data/ex1_5-out.csv @@ -0,0 +1,4 @@ +a,b,c,min,max,mean +580,250,462,250,580,430.6666666666667 +325,950,740,325,950,671.6666666666666 +215,546,730,215,730,497 diff --git a/examples/ex1_5.js b/examples/ex1_5.js new file mode 100644 index 0000000..0d49b52 --- /dev/null +++ b/examples/ex1_5.js @@ -0,0 +1,28 @@ +// ## Example 1.5: Duplicate input rows to the output +// +// Use the spread syntax (...) to concisely duplicate input rows to the output, in both the transformation function +// and the `handleHeaders` function. +// +// Setting `handleHeaders` to a separate function is convenient to handle its logic separately from the data rows. +// Using a transformation function instead of a hardcoded array is useful if the input row headers are unknown +// or other arbitrary logic is required to determine the output header names. + +import { CSVReader, CSVTransformer, CSVWriter } from '../src/index.js'; + +// It is useful to split the header transformation into a separate function because the logic for the header +// is likely different from the rest of the CSV. +function handleHeaders(headers) { + return [...headers, 'min', 'max', 'mean']; // Duplicate input headers as the first headers in the output +} + +function calculate(row) { + const numbers = row.map(Number); + const min = Math.min(...numbers); + const max = Math.max(...numbers); + const mean = numbers.reduce((a, n) => a + n, 0) / numbers.length; + return [...row, min, max, mean]; // Duplicate input rows as the first columns in the output +} + +await new CSVReader(new URL('./data/ex1_5-in.csv', import.meta.url)) + .pipeThrough(new CSVTransformer(calculate, { handleHeaders })) + .pipeTo(new CSVWriter(new URL('./data/ex1_5-out.csv', import.meta.url))); \ No newline at end of file