I'm really excited about Bun and look forward to trying it out more and more.
Today I needed a quick script to parse a CSV file to compute some simple arithmetic on some numbers in it.
To do that, here's what I did:
bun init
bun install csv-simple-parser
code index.ts
And the code:
import parse from "csv-simple-parser";
console.time("total");
const numbers: number[] = [];
const file = Bun.file(process.argv.slice(2)[0]);
type Rec = {
Pageviews: string;
};
const csv = parse(await file.text(), { header: true }) as Rec[];
for (const row of csv) {
numbers.push(parseInt(row["Pageviews"] || "0"));
}
console.timeEnd("total");
console.log("Mean ", numbers.reduce((a, b) => a + b, 0) / numbers.length);
console.log("Median", numbers.sort()[Math.floor(numbers.length / 2)]);
And running it:
❯ wc -l file.csv
13623 file.csv
❯ /usr/bin/time bun run index.ts file.csv
[8.20ms] total
Mean 7.205534757395581
Median 1
0.04 real 0.03 user 0.01 sys
(On my Intel MacBook Pro...) The reading in the file and parsing the 13k lines took 8.2 milliseconds. The whole execution took 0.04 seconds. Pretty neat.
Comments