Skip to content

Commit a759353

Browse files
committed
refactor: simplify wc implemention
1 parent 481e074 commit a759353

1 file changed

Lines changed: 19 additions & 30 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.mjs

Lines changed: 19 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,9 @@ program.parse();
1414

1515
const paths = program.args;
1616
const options = program.opts();
17+
const noFlag = !options.l && !options.w && !options.c;
1718

18-
const total = {
19-
linesCounter: 0,
20-
wordsCounter: 0,
21-
characterCounter: 0,
22-
};
19+
const total = {};
2320
let hadError = false;
2421
for (const path of paths) {
2522
try {
@@ -31,39 +28,31 @@ for (const path of paths) {
3128
trimmedContent === "" ? 0 : trimmedContent.split(/\s+/).length;
3229
const characterCounter = content.length;
3330

34-
total.linesCounter += linesCounter;
35-
total.wordsCounter += wordsCounter;
36-
total.characterCounter += characterCounter;
37-
38-
let results = [];
39-
if (options.l) results.push(linesCounter);
40-
if (options.w) results.push(wordsCounter);
41-
if (options.c) results.push(characterCounter);
31+
const results = [];
32+
if (options.l || noFlag) {
33+
results.push(linesCounter);
34+
total["lineCounter"] = (total["lineCounter"] ?? 0) + linesCounter;
35+
}
36+
if (options.w || noFlag) {
37+
results.push(wordsCounter);
38+
total["wordsCounter"] = (total["wordsCounter"] ?? 0) + wordsCounter;
39+
}
40+
if (options.c || noFlag) {
41+
results.push(characterCounter);
42+
total["characterCounter"] =
43+
(total["characterCounter"] ?? 0) + characterCounter;
44+
}
4245

43-
if (!options.l && !options.w && !options.c)
44-
console.log(
45-
` ${linesCounter} ${wordsCounter} ${characterCounter} ${path}`,
46-
);
47-
else {
4846
console.log(results.join(" ") + " " + path);
49-
}
47+
5048
} catch (error) {
5149
console.error(error.message);
5250
hadError = true;
5351
}
5452
}
5553
if (paths.length > 1) {
56-
if (!options.l && !options.w && !options.c) {
57-
console.log(
58-
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
59-
);
60-
} else {
61-
const totalWithFlags = [];
62-
if (options.l) totalWithFlags.push(total.linesCounter);
63-
if (options.w) totalWithFlags.push(total.wordsCounter);
64-
if (options.c) totalWithFlags.push(total.characterCounter);
65-
console.log(totalWithFlags.join(" ") + " total");
66-
}
54+
55+
console.log(Object.values(total).join(" "),"total")
6756
}
6857
if (hadError) {
6958
process.exitCode = 1;

0 commit comments

Comments
 (0)