Skip to content

Commit 7a43ee8

Browse files
committed
Implement wc command to count lines, words and characters
1 parent 5684c37 commit 7a43ee8

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
import process from "node:process";
4+
5+
program
6+
.name("wc command")
7+
.description("Implement wc command to count words and lines")
8+
.option("-l,", "show number of lines only")
9+
.option("-w,", "show number of words only")
10+
.option("-c,", "show number of characters only")
11+
.argument("[path...]", "The file path to process");
12+
13+
program.parse(process.argv);
14+
15+
const opts = program.opts();
16+
let paths = program.args;
17+
18+
if (paths.length === 0) {
19+
console.error("wc: no file specified");
20+
process.exit(1);
21+
}
22+
23+
let totals = { lines: 0, words: 0, chars: 0 };
24+
25+
for (const filePath of paths) {
26+
let content;
27+
try {
28+
content = await fs.readFile(filePath, "utf8");
29+
} catch (err) {
30+
console.error(`wc: cannot read file "${filePath}": ${err.message}`);
31+
continue; // move on to next path
32+
}
33+
34+
const lineCount = content.split("n").length;
35+
36+
const wordCount = content.split(/\s+/).filter(Boolean).length;
37+
38+
const charCount = content.length;
39+
40+
totals.lines += lineCount;
41+
totals.words += wordCount;
42+
totals.chars += charCount;
43+
44+
// Decide what to print depending on flags
45+
if (!opts.l && !opts.w && !opts.c) {
46+
console.log(`${lineCount} ${wordCount} ${charCount} ${filePath}`);
47+
continue;
48+
}
49+
50+
if (opts.l) {
51+
console.log(`${lineCount} ${filePath}`);
52+
}
53+
54+
if (opts.w) {
55+
console.log(`${wordCount} ${filePath}`);
56+
}
57+
58+
if (opts.c) {
59+
console.log(`${charCount} ${filePath}`);
60+
}
61+
}
62+
63+
//Print totals if there are multiple files
64+
if (paths.length > 1) {
65+
if (!opts.l && !opts.w && !opts.c) {
66+
console.log(`${totals.lines} ${totals.words} ${totals.chars} total`);
67+
}
68+
69+
if (opts.l) {
70+
console.log(`${totals.lines} total`);
71+
}
72+
73+
if (opts.w) {
74+
console.log(`${totals.words} total`);
75+
}
76+
77+
if (opts.c) {
78+
console.log(`${totals.chars} total`);
79+
}
80+
}

0 commit comments

Comments
 (0)