Skip to content

Commit d0e165c

Browse files
committed
fixed the wc implementation to support multiple flags at the same time.
1 parent 6d08c59 commit d0e165c

1 file changed

Lines changed: 43 additions & 27 deletions

File tree

implement-shell-tools/wc/my-wc.js

Lines changed: 43 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@
33
const fs = require("node:fs");
44

55
function countFile(filePath) {
6+
const stats = fs.statSync(filePath);
7+
8+
if (!stats.isFile()) {
9+
console.warn(`${filePath} is not a file, skipping`);
10+
return null;
11+
}
612
const content = fs.readFileSync(filePath, "utf8");
713

814
const lines = content.split("\n").length - 1;
@@ -15,49 +21,59 @@ function countFile(filePath) {
1521
function main() {
1622
const args = process.argv.slice(2);
1723

18-
let flag = null;
24+
let flags = [];
1925
let files = [];
2026

27+
// 1 Parse args
2128
for (const arg of args) {
2229
if (arg === "-l" || arg === "-w" || arg === "-c") {
23-
flag = arg;
30+
flags.push(arg);
2431
} else {
2532
files.push(arg);
2633
}
2734
}
2835

36+
//2 Helper function that decides what to print
37+
38+
function formatOutput(counts, files) {
39+
const parts = [];
40+
41+
// if no flags show everything
42+
const showAll = flags.length === 0;
43+
44+
if (showAll || flags.includes("-l"))parts.push(counts.lines);
45+
if (showAll || flags.includes("-w"))parts.push(counts.words);
46+
if (showAll || flags.includes("-c"))parts.push(counts.chars);
47+
48+
parts.push(files);
49+
50+
return parts.join(" ");
51+
}
52+
// 3 totals
2953
let totalLines = 0;
3054
let totalWords = 0;
3155
let totalChars = 0;
3256

57+
58+
// 4 per-file output
3359
for (const file of files) {
34-
const { lines, words, chars } = countFile(file);
35-
36-
totalLines += lines;
37-
totalWords += words;
38-
totalChars += chars;
39-
40-
if (flag === "-l") {
41-
console.log(`${lines} ${file}`);
42-
} else if (flag === "-w") {
43-
console.log(`${words} ${file}`);
44-
} else if (flag === "-c") {
45-
console.log(`${chars} ${file}`);
46-
} else {
47-
console.log(`${lines} ${words} ${chars} ${file}`);
48-
}
49-
}
60+
const counts = countFile(file);
61+
if (!counts) continue;
5062

63+
totalLines += counts.lines;
64+
totalWords += counts.words;
65+
totalChars += counts.chars;
66+
67+
console.log(formatOutput(counts, files));
68+
}
69+
// 5 Total output (only if multiple files)
5170
if (files.length > 1) {
52-
if (flag === "-l") {
53-
console.log(`${totalLines} total`);
54-
} else if (flag === "-w") {
55-
console.log(`${totalWords} total`);
56-
} else if (flag === "-c") {
57-
console.log(`${totalChars} total`);
58-
} else {
59-
console.log(`${totalLines} ${totalWords} ${totalChars} total`);
60-
}
71+
const totalCounts = {
72+
lines: totalLines,
73+
words: totalWords,
74+
chars: totalChars,
75+
};
76+
console.log(formatOutput(totalCounts,"total"));
6177
}
6278
}
6379

0 commit comments

Comments
 (0)