Skip to content

Commit 78bdfd5

Browse files
committed
cat implemented
1 parent 3f26722 commit 78bdfd5

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

  • implement-shell-tools/cat

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const fs = require("fs");
2+
3+
const arguments = process.argv;
4+
const filePaths = arguments.slice(2);
5+
6+
const index = arguments[1].lastIndexOf("/");
7+
const currentWorkingDirectory = arguments[1].slice(0, index + 1);
8+
9+
let flag = filePaths[0];
10+
if (flag.charAt(0) == "-") {
11+
flag = filePaths.shift();
12+
}
13+
14+
function splitFile(fileName) {
15+
const filePath = currentWorkingDirectory + fileName;
16+
const text = fs.readFileSync(filePath, "utf8").trimEnd();
17+
return text.split("\n");
18+
}
19+
20+
function printFile(lines) {
21+
lines.forEach((line) => {
22+
console.log(line);
23+
});
24+
}
25+
26+
function executeFlag(lines) {
27+
if (flag === "-n") {
28+
return lines.map((line, index) => `${String(index + 1).padStart(6, " ")} ${line}`);
29+
} else if (flag === "-b") {
30+
let lineNumber = 1;
31+
return lines.map((line) => {
32+
if (line === "") {
33+
return `${line}`;
34+
}
35+
return `${String(lineNumber++).padStart(6, " ")} ${line}`;
36+
});
37+
} else {
38+
return lines;
39+
}
40+
}
41+
42+
filePaths.forEach((filePath) => {
43+
let lines = splitFile(filePath);
44+
lines = executeFlag(lines);
45+
printFile(lines);
46+
});

0 commit comments

Comments
 (0)