Skip to content

Commit 3de9968

Browse files
committed
Removing duplication of output code with a helper function.
1 parent 9463024 commit 3de9968

File tree

1 file changed

+23
-23
lines changed
  • implement-shell-tools/wc

1 file changed

+23
-23
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,18 @@ async function getCounts(file){
2323
const byteCount = Buffer.byteLength(content, "utf-8"); //Calculate how many bytes the string uses in UTF-8 (important because some characters use more than 1 byte)
2424
return { lineCount, wordCount, byteCount };
2525
}
26-
//initiating totals
26+
//helper to remove duplicated output logic
27+
function formatOutput(lines, words, bytes, filename, options) {
28+
let formattedOutput = "";
29+
if (options.lines) formattedOutput += `${lines} `;
30+
if (options.words) formattedOutput+= `${words} `;
31+
if (options.bytes) formattedOutput += `${bytes} `;
32+
if (!options.lines && !options.words && !options.bytes) { // default: print all three
33+
formattedOutput += `${lines} ${words} ${bytes} `;
34+
}
35+
return formattedOutput + filename;
36+
}
37+
//Initiating totals
2738
let totalLines = 0;
2839
let totalWords = 0;
2940
let totalBytes = 0;
@@ -35,27 +46,16 @@ for (const file of files) {
3546
totalWords += wordCount;
3647
totalBytes += byteCount;
3748

38-
let output = "";
39-
if (options.lines) output += `${lineCount} `;
40-
if (options.words) output += `${wordCount} `;
41-
if (options.bytes) output += `${byteCount} `;
42-
if (!options.lines && !options.words && !options.bytes) {
43-
output += `${lineCount} ${wordCount} ${byteCount} `;
44-
}
45-
output += file;
46-
console.log(output);
49+
const formatted = formatOutput(lineCount, wordCount, byteCount, file, options);
50+
console.log(formatted);
4751
}
48-
49-
50-
//Print totals if multiple files
52+
//Print totals if multiple files
5153
if (files.length > 1) {
52-
let totalOutput = "";
53-
if (options.lines) totalOutput += `${totalLines} `;
54-
if (options.words) totalOutput += `${totalWords} `;
55-
if (options.bytes) totalOutput += `${totalBytes} `;
56-
if (!options.lines && !options.words && !options.bytes) {
57-
totalOutput += `${totalLines} ${totalWords} ${totalBytes} `;
58-
}
59-
totalOutput += "total";
60-
console.log(totalOutput);
61-
}
54+
const formattedTotals = formatOutput(totalLines, totalWords, totalBytes, "total", options);
55+
console.log(formattedTotals);
56+
}
57+
58+
59+
60+
61+

0 commit comments

Comments
 (0)