Skip to content

Commit 6caee3c

Browse files
committed
Complete the cat implementation
1 parent ddbae1a commit 6caee3c

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

implement-shell-tools/cat/cat.mjs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,53 @@ program.parse();
1010

1111
const { number, numberNonblank } = program.opts();
1212
const paths = program.args;
13+
14+
async function processFile(path) {
15+
try {
16+
const stat = await fs.stat(path);
17+
18+
if (stat.isDirectory()) {
19+
console.error(`${path}: Is a directory`);
20+
return;
21+
}
22+
23+
const content = await fs.readFile(path, { encoding: "utf-8" });
24+
const lines = content.split("\n");
25+
const hasTrailingNewLine = content.endsWith("\n");
26+
const effectiveLines = hasTrailingNewLine ? lines.slice(0, -1) : lines;
27+
let lineNumber = 1;
28+
29+
const processed = effectiveLines.map((line) => {
30+
if (numberNonblank) {
31+
if (line.trim() !== "") {
32+
const result = `${lineNumber}\t${line}`;
33+
lineNumber += 1;
34+
return result;
35+
}
36+
37+
return line;
38+
}
39+
40+
if (number) {
41+
const result = `${lineNumber}\t${line}`;
42+
lineNumber += 1;
43+
return result;
44+
}
45+
46+
return line;
47+
});
48+
49+
const output = processed.join("\n");
50+
console.log(output);
51+
} catch (error) {
52+
console.error(`${path}: ${error.message}`);
53+
}
54+
}
55+
56+
try {
57+
for (const path of paths) {
58+
await processFile(path);
59+
}
60+
} catch (error) {
61+
console.error(error.message);
62+
}

0 commit comments

Comments
 (0)