Skip to content

Commit 637b764

Browse files
committed
Add -b flag to number non-empty lines
1 parent dba8fd3 commit 637b764

1 file changed

Lines changed: 25 additions & 10 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.js

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,20 @@ import { promises as fs } from "node:fs";
33

44
const args = process.argv.slice(2);
55

6-
let showNumbers = false;
6+
let option = "none";
77
const paths = [];
88

9+
910
for (const arg of args) {
1011
if (arg === "-n") {
11-
showNumbers = true;
12+
option = "n";
13+
} else if (arg === "-b") {
14+
option = "b";
1215
} else {
1316
paths.push(arg);
1417
}
1518
}
1619

17-
1820
if (paths.length === 0) {
1921
console.error("Expected at least one file path.");
2022
process.exit(1);
@@ -25,15 +27,28 @@ for (const path of paths) {
2527

2628
const lines = content.split("\n");
2729

28-
if (showNumbers) {
29-
let i = 1;
30+
let lineNumber = 1;
31+
32+
for (const line of lines) {
3033

31-
for (const line of lines) {
32-
console.log(`${i} ${line}`);
33-
i++;
34+
if (option === "n") {
35+
console.log(`${lineNumber} ${line}`);
36+
lineNumber++;
3437
}
3538

36-
} else {
37-
console.log(content);
39+
else if (option === "b") {
40+
41+
if (line !== "") {
42+
console.log(`${lineNumber} ${line}`);
43+
lineNumber++;
44+
} else {
45+
console.log("");
46+
}
47+
48+
}
49+
50+
else {
51+
console.log(line);
52+
}
3853
}
3954
}

0 commit comments

Comments
 (0)