Skip to content

Commit e5788f8

Browse files
committed
refactor: Simplify output formatting and fix line count calculation
1 parent 6f08d18 commit e5788f8

File tree

1 file changed

+17
-19
lines changed
  • implement-shell-tools/wc

1 file changed

+17
-19
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,44 +14,42 @@ program.parse();
1414
const options = program.opts();
1515
const filePaths = program.args;
1616

17+
function formatCounts(lines, words, chars, options) {
18+
let result = "";
19+
20+
if (options.l || options.w || options.c) {
21+
if (options.l) result += `${lines} `;
22+
if (options.w) result += `${words} `;
23+
if (options.c) result += `${chars} `;
24+
} else {
25+
result += `${lines} ${words} ${chars} `;
26+
}
27+
28+
return result;
29+
}
30+
1731
let totalLines = 0;
1832
let totalWords = 0;
1933
let totalChars = 0;
2034

2135
for (const filePath of filePaths) {
2236
const content = await fs.readFile(filePath, "utf-8");
2337

24-
const lineCount = content.split("\n").length;
38+
const lineCount = (content.match(/\n/g) || []).length;
2539
const wordCount = content.trim().split(/\s+/).length;
2640
const charCount = content.length;
2741

2842
totalLines += lineCount;
2943
totalWords += wordCount;
3044
totalChars += charCount;
3145

32-
let output = "";
33-
34-
if (options.l || options.w || options.c) {
35-
if (options.l) output += `${lineCount} `;
36-
if (options.w) output += `${wordCount} `;
37-
if (options.c) output += `${charCount} `;
38-
} else {
39-
output += `${lineCount} ${wordCount} ${charCount} `;
40-
}
46+
const output = formatCounts(lineCount, wordCount, charCount, options);
4147

4248
console.log(`${output}${filePath}`);
4349
}
4450

4551
if (filePaths.length > 1) {
46-
let totalOutput = "";
47-
48-
if (options.l || options.w || options.c) {
49-
if (options.l) totalOutput += `${totalLines} `;
50-
if (options.w) totalOutput += `${totalWords} `;
51-
if (options.c) totalOutput += `${totalChars} `;
52-
} else {
53-
totalOutput += `${totalLines} ${totalWords} ${totalChars} `;
54-
}
52+
const totalOutput = formatCounts(totalLines, totalWords, totalChars, options);
5553

5654
console.log(`${totalOutput}total`);
5755
}

0 commit comments

Comments
 (0)