Skip to content

Commit 4aaf1c1

Browse files
committed
Refactor output handling in cat, ls, and wc commands for improved formatting
1 parent 0cf4afc commit 4aaf1c1

3 files changed

Lines changed: 23 additions & 28 deletions

File tree

‎implement-shell-tools/cat/cat.js‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ let lineNumber = 1;
2525
for (const file of files) {
2626
try {
2727
const contents = fs.readFileSync(file, "utf8");
28-
const lines = contents.split("\n");
28+
const hasTrailingNewline = contents.endsWith("\n");
29+
const lines = hasTrailingNewline
30+
? contents.slice(0, -1).split("\n")
31+
: contents.split("\n");
2932

3033
lines.forEach((line, index) => {
31-
const output = index < lines.length - 1 ? line + "\n" : line;
34+
const output =
35+
index < lines.length - 1 || hasTrailingNewline ? line + "\n" : line;
3236

3337
if (numberNonBlank) {
3438
if (line.trim() === "") {

‎implement-shell-tools/ls/ls.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ for (let i = 0; i < paths.length; i++) {
4343
}
4444

4545
if (!onePerLine) {
46-
console.log();
46+
process.stdout.write("\n");
4747
}
4848
}
4949
} catch (error) {

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

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,20 @@ let totalWords = 0;
3131
let totalBytes = 0;
3232
let filesCounted = 0;
3333

34+
function formatResult(lines, words, bytes, fileName) {
35+
let result = "";
36+
if (countLines) {
37+
result += String(lines).padStart(8);
38+
}
39+
if (countWords) {
40+
result += String(words).padStart(8);
41+
}
42+
if (countBytes) {
43+
result += String(bytes).padStart(8);
44+
}
45+
return result + " " + fileName;
46+
}
47+
3448
function countFile(fileName) {
3549
try {
3650
const content = fs.readFileSync(fileName, "utf8");
@@ -44,18 +58,7 @@ function countFile(fileName) {
4458
totalWords += words;
4559
totalBytes += bytes;
4660
filesCounted++;
47-
let result = "";
48-
if (countLines) {
49-
result += lines + " ";
50-
}
51-
if (countWords) {
52-
result += words + " ";
53-
}
54-
if (countBytes) {
55-
result += bytes + " ";
56-
}
57-
result += fileName;
58-
console.log(result);
61+
console.log(formatResult(lines, words, bytes, fileName));
5962
} catch (error) {
6063
console.log("Cannot read file: " + fileName);
6164
}
@@ -66,17 +69,5 @@ for (let file of files) {
6669
}
6770

6871
if (filesCounted > 1) {
69-
let result = "";
70-
if (countLines) {
71-
result += totalLines + " ";
72-
}
73-
if (countWords) {
74-
result += totalWords + " ";
75-
}
76-
if (countBytes) {
77-
result += totalBytes + " ";
78-
}
79-
result += "total";
80-
81-
console.log(result);
72+
console.log(formatResult(totalLines, totalWords, totalBytes, "total"));
8273
}

0 commit comments

Comments
 (0)