Skip to content

Commit ac09bd5

Browse files
handling of total updated on wc
1 parent 96f5489 commit ac09bd5

1 file changed

Lines changed: 33 additions & 7 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,16 @@ for (const path of filePaths) {
2929
let fileStats;
3030
let fileData = {};
3131

32+
// Count of flags and arguments provided -- basically state
33+
fileData.countOfFlags = Object.values(program.opts()).filter(Boolean).length;
34+
fileData.filePaths = filePaths.length;
35+
3236
fileContent = await fs.readFile(path, "utf-8");
3337

38+
if (fileContent.endsWith("\n")) {
39+
fileContent = fileContent.slice(0, -1);
40+
}
41+
3442
fileData.lineCount = getLineCount(fileContent);
3543
lineCountTotal += fileData.lineCount;
3644

@@ -49,17 +57,35 @@ console.log(outputData.map(formatOutput).join("\n"));
4957

5058
if (filePaths.length > 1) {
5159
console.log(
52-
`${String(lineCountTotal).padStart(3)}${String(wordCountTotal).padStart(
53-
4
54-
)}${String(fileSizeTotal).padStart(4)} total`
60+
formatOutput({
61+
lineCount: lineCountTotal,
62+
wordCount: wordCountTotal,
63+
fileSize: fileSizeTotal,
64+
path: "total",
65+
})
5566
);
5667
}
5768

58-
function formatOutput({ lineCount, wordCount, fileSize, path }) {
69+
function formatOutput({
70+
lineCount,
71+
wordCount,
72+
fileSize,
73+
path,
74+
countOfFlags,
75+
filePaths,
76+
}) {
5977
let output = [];
60-
if (lines || showAll) output.push(String(lineCount).padStart(3));
61-
if (words || showAll) output.push(String(wordCount).padStart(4));
62-
if (bytes || showAll) output.push(String(fileSize).padStart(4));
78+
79+
// I've added this if statement as I found my node wc output looked misaligned compared to the Unix wc output when only one flag and one file were provided.
80+
if (countOfFlags === 1 && filePaths <= 1) {
81+
if (lines || showAll) output.push(String(lineCount));
82+
if (words || showAll) output.push(String(wordCount));
83+
if (bytes || showAll) output.push(String(fileSize));
84+
} else {
85+
if (lines || showAll) output.push(String(lineCount).padStart(3));
86+
if (words || showAll) output.push(String(wordCount).padStart(4));
87+
if (bytes || showAll) output.push(String(fileSize).padStart(4));
88+
}
6389

6490
return `${output.join("")} ${path}`;
6591
}

0 commit comments

Comments
 (0)