Skip to content

Commit 2b10b68

Browse files
Add flag support to wc (-l, -w, -c)
1 parent 661a148 commit 2b10b68

File tree

1 file changed

+27
-6
lines changed
  • implement-shell-tools/wc

1 file changed

+27
-6
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ program
77
.description(
88
"The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input"
99
)
10+
.option("-l, --lines", "count lines only")
11+
.option("-w, --words", "count words only")
12+
.option("-c, --bytes", "count bytes only")
1013
.argument("<path...>", "The file paths to process");
1114

1215
//interpret the program
@@ -15,7 +18,25 @@ program.parse();
1518
//initialise totals
1619
let totalLines = 0;
1720
let totalWords = 0;
18-
let totalCharacters = 0;
21+
let totalBytes = 0;
22+
23+
//check for flags
24+
const hasLineFlag = program.opts().lines;
25+
const hasWordFlag = program.opts().words;
26+
const hasBytesFlag = program.opts().bytes;
27+
28+
// create output format function to avoid repetition
29+
function formatOutput(lines, words, bytes, path) {
30+
if (hasLineFlag) {
31+
console.log(`${lines} ${path}`);
32+
} else if (hasWordFlag) {
33+
console.log(`${words} ${path}`);
34+
} else if (hasBytesFlag) {
35+
console.log(`${bytes} ${path}`);
36+
} else {
37+
console.log(`${lines} ${words} ${bytes} ${path}`);
38+
}
39+
}
1940

2041
//process each file
2142

@@ -29,17 +50,17 @@ for (const path of program.args) {
2950
//count words (split by any whitespace)
3051
const words = content.split(/\s+/).filter((word) => word.length > 0).length;
3152

32-
//count character
33-
const characters = content.length;
53+
//count bytes correctly especially important for non-ASCII characters
54+
const bytes = Buffer.byteLength(content, "utf-8");
3455

3556
//Add to totals
3657
totalLines += lines;
3758
totalWords += words;
38-
totalCharacters += characters;
59+
totalBytes += bytes;
3960

40-
console.log(`${lines} ${words} ${characters} ${path}`);
61+
formatOutput(lines, words, bytes, path);
4162
}
4263

4364
if (program.args.length > 1) {
44-
console.log(`${totalLines} ${totalWords} ${totalCharacters} total`);
65+
formatOutput(totalLines, totalWords, totalBytes, "total");
4566
}

0 commit comments

Comments
 (0)