Skip to content

Commit 661a148

Browse files
Implement wc with multiple file support and totals
1 parent 668b8ce commit 661a148

File tree

1 file changed

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

1 file changed

+27
-12
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,39 @@ 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-
.argument("<path>", "The file path to process");
10+
.argument("<path...>", "The file paths to process");
1111

1212
//interpret the program
1313
program.parse();
1414

15-
//use the parsed data
16-
const path = program.args[0];
15+
//initialise totals
16+
let totalLines = 0;
17+
let totalWords = 0;
18+
let totalCharacters = 0;
1719

18-
//read the file
19-
const content = await fs.readFile(path, "utf-8");
20+
//process each file
2021

21-
//count lines
22-
const lines = content.split("\n").length - 1;
22+
for (const path of program.args) {
23+
//read the file
24+
const content = await fs.readFile(path, "utf-8");
2325

24-
//count words split by any whitespace
25-
const words = content.split(/\s+/).filter((word) => word.length > 0).length;
26+
//count lines
27+
const lines = content.split("\n").length - 1;
2628

27-
//count character
28-
const characters = content.length;
29+
//count words (split by any whitespace)
30+
const words = content.split(/\s+/).filter((word) => word.length > 0).length;
2931

30-
console.log(`${lines} ${words} ${characters} ${path}`);
32+
//count character
33+
const characters = content.length;
34+
35+
//Add to totals
36+
totalLines += lines;
37+
totalWords += words;
38+
totalCharacters += characters;
39+
40+
console.log(`${lines} ${words} ${characters} ${path}`);
41+
}
42+
43+
if (program.args.length > 1) {
44+
console.log(`${totalLines} ${totalWords} ${totalCharacters} total`);
45+
}

0 commit comments

Comments
 (0)