Skip to content

Commit 90398dd

Browse files
author
Fatma Degirmenci
committed
implement wc command
1 parent 07dd218 commit 90398dd

File tree

1 file changed

+53
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+53
-0
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
2+
import { program } from "commander";
3+
import { promises as fs } from "node:fs";
4+
5+
program
6+
.option("-l", "Print only the line count")
7+
.option("-w", "Print only the word count")
8+
.option("-c", "Print only the byte count")
9+
.argument("<paths...>", "One or more file paths");
10+
11+
program.parse();
12+
13+
const opts = program.opts();
14+
const paths = program.args;
15+
16+
async function wcFile(path) {
17+
const content = await fs.readFile(path, "utf8");
18+
19+
const lines = content.split("\n").length;
20+
const words = content.trim().split(/\s+/).filter(Boolean).length;
21+
const bytes = Buffer.byteLength(content, "utf8");
22+
23+
return { lines, words, bytes };
24+
}
25+
26+
function formatOutput(counts, filename, opts) {
27+
if (opts.l) return `${counts.lines} ${filename}`;
28+
if (opts.w) return `${counts.words} ${filename}`;
29+
if (opts.c) return `${counts.bytes} ${filename}`;
30+
31+
return `${counts.lines} ${counts.words} ${counts.bytes} ${filename}`;
32+
}
33+
34+
async function main() {
35+
let total = { lines: 0, words: 0, bytes: 0 };
36+
let multipleFiles = paths.length > 1;
37+
38+
for (const path of paths) {
39+
const counts = await wcFile(path);
40+
41+
total.lines += counts.lines;
42+
total.words += counts.words;
43+
total.bytes += counts.bytes;
44+
45+
console.log(formatOutput(counts, path, opts));
46+
}
47+
48+
if (multipleFiles) {
49+
console.log(formatOutput(total, "total", opts));
50+
}
51+
}
52+
53+
main();

0 commit comments

Comments
 (0)