Skip to content

Commit e520324

Browse files
Refactor: address PR feedback for cat and ls tools
1 parent b91a308 commit e520324

File tree

3 files changed

+19
-18
lines changed

3 files changed

+19
-18
lines changed

.gitignore

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
2+
prep
13
node_modules
2-
prep/
3-
node_modules/
4+
.venv

implement-shell-tools/cat/cat.js

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,33 +22,29 @@ let lineNumber = 0;
2222
// Process each file
2323
for (const path of program.args) {
2424
const hasNumberFlag = program.opts().number; // True if user used -n flag
25-
const hasBFlag = program.opts().numberNonBlank;
25+
const shouldNumberNonBlank = program.opts().numberNonBlank;
2626

2727
//read the file for each argument
2828
const content = await fs.readFile(path, "utf-8");
29+
const lines = content.split("\n"); // Split into array of lines
30+
2931
// Output with or without line numbers
3032
if (hasNumberFlag) {
3133
// Add line numbers to each line
32-
const lines = content.split("\n"); // Split into array of lines
3334
const numberedLines = lines.map((line) => {
3435
lineNumber = lineNumber + 1;
3536
return `${lineNumber} ${line}`; // Format: " 1 Hello"
3637
});
3738
console.log(numberedLines.join("\n")); // Join back with newlines
38-
} else if (hasBFlag) {
39-
const lines = content.split("\n");
39+
} else if (shouldNumberNonBlank) {
4040

4141
const numberedLines = lines.map((line) => {
42-
if (line.trim() === "") {
43-
return line;
44-
} else {
45-
lineNumber = lineNumber + 1;
46-
return ` ${lineNumber} ${line}`;
47-
}
42+
return line.trim() === "" ? line : `${++lineNumber} ${line}`;
4843
});
4944
console.log(numberedLines.join("\n"));
5045
} else {
5146
// Just print the file as-is
5247
console.log(content);
5348
}
5449
}
50+

implement-shell-tools/ls/ls.js

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const files = await fs.readdir(directory);
2424

2525
//check for flags
2626
const hasAflag = program.opts().all;
27+
const hasOneFlag = program.opts().one;
2728

2829
// Filter the files array BEFORE looping
2930
// If hasAflag is true, keep all files
@@ -34,10 +35,13 @@ const fileToShow = hasAflag
3435
: files.filter(file => !file.startsWith("."))
3536

3637

37-
//print each file on its own line
38-
// Note: console.log(files) would print the entire array like: ['file1', 'file2']
39-
// Loop prints each individually on separate lines
38+
if (hasOneFlag) {
39+
40+
for (const file of fileToShow) {
41+
console.log(file);
42+
}
43+
} else {
44+
// print horizontally
45+
console.log(fileToShow.join(" "));
46+
}
4047

41-
for (const file of fileToShow) {
42-
console.log(file)
43-
}

0 commit comments

Comments
 (0)