Skip to content

Commit bc95366

Browse files
committed
Match wc output formatting and support total counts
1 parent d66bde8 commit bc95366

1 file changed

Lines changed: 33 additions & 10 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ let showLines = false;
88
let fileNames = [];
99

1010
// Check flags and file names
11-
for (let item of args) {
11+
for (const item of args) {
1212
if (item === "-l") {
1313
showLines = true;
1414
} else if (item === "-w") {
@@ -27,20 +27,43 @@ if (!showLines && !showWords && !showChars) {
2727
showChars = true;
2828
}
2929

30-
for (let fileName of fileNames) {
31-
let text = fs.readFileSync(fileName, "utf8");
30+
let grandLines = 0;
31+
let grandWords = 0;
32+
let grandChars = 0;
3233

33-
let totalLines = text.split("\n").length - 1;
34-
let totalWords = text.trim().split(/\s+/).length;
35-
let totalChars = Buffer.byteLength(text);
34+
for (const fileName of fileNames) {
35+
const text = fs.readFileSync(fileName, "utf8");
3636

37+
const totalLines = text.split("\n").length - 1;
38+
39+
const trimmed = text.trim();
40+
const totalWords = trimmed ? trimmed.split(/\s+/).length : 0;
41+
42+
const totalChars = Buffer.byteLength(text);
43+
44+
grandLines += totalLines;
45+
grandWords += totalWords;
46+
grandChars += totalChars;
47+
48+
let output = "";
49+
50+
if (showLines) output += String(totalLines).padStart(8);
51+
if (showWords) output += String(totalWords).padStart(8);
52+
if (showChars) output += String(totalChars).padStart(8);
53+
54+
output += " " + fileName;
55+
56+
console.log(output);
57+
}
58+
59+
if (fileNames.length > 1) {
3760
let output = "";
3861

39-
if (showLines) output += totalLines + " ";
40-
if (showWords) output += totalWords + " ";
41-
if (showChars) output += totalChars + " ";
62+
if (showLines) output += String(grandLines).padStart(8);
63+
if (showWords) output += String(grandWords).padStart(8);
64+
if (showChars) output += String(grandChars).padStart(8);
4265

43-
output += fileName;
66+
output += " total";
4467

4568
console.log(output);
4669
}

0 commit comments

Comments
 (0)