Skip to content

Commit 029b379

Browse files
committed
chore: final review and cleanup of cat, ls and wc implementations
2 parents b8b055e + 57768d0 commit 029b379

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

implement-shell-tools/ls/ls.mjs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { promises as fs } from "node:fs";
22
import { program } from "commander";
3-
import { dirxml } from "node:console";
43

54
program
65
.name("ls ")

implement-shell-tools/wc/wc.mjs

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ program
66
.name("wc")
77
.description("wc implementation")
88
.argument("<paths...>", "the file path to process")
9-
.option("-l", "count how many lines");
9+
.option("-l", "count lines")
10+
.option("-w", "count words")
11+
.option("-c", "count characters");
12+
1013
program.parse();
1114

1215

@@ -17,13 +20,15 @@ if (paths.length === 0) {
1720
process.exit(1);
1821
}
1922

20-
2123
const options = program.opts();
24+
2225
const total = {
2326
linesCounter: 0,
2427
wordsCounter: 0,
2528
characterCounter: 0,
2629
};
30+
31+
2732
try {
2833
for (const path of paths) {
2934
const content = await fs.readFile(path, "utf-8");
@@ -36,21 +41,30 @@ try {
3641
total.wordsCounter += wordsCounter;
3742
total.characterCounter += characterCounter;
3843

39-
if (options.l) {
40-
console.log(`${linesCounter} ${path}`);
41-
} else {
44+
let results = [];
45+
if (options.l) results.push(linesCounter);
46+
if (options.w) results.push(wordsCounter);
47+
if (options.c) results.push(characterCounter);
48+
49+
if (!options.l && !options.w && !options.c)
4250
console.log(
4351
` ${linesCounter} ${wordsCounter} ${characterCounter} ${path}`,
4452
);
53+
else {
54+
console.log(results.join(" ") + " " + path);
4555
}
4656
}
4757
if (paths.length > 1) {
48-
if (options.l) {
49-
console.log(`${total.linesCounter} total`);
50-
} else {
58+
if (!options.l && !options.w && !options.c) {
5159
console.log(
5260
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
5361
);
62+
} else {
63+
const totalWithFlags = [];
64+
if (options.l) totalWithFlags.push(total.linesCounter);
65+
if (options.w) totalWithFlags.push(total.wordsCounter);
66+
if (options.c) totalWithFlags.push(total.characterCounter);
67+
console.log(totalWithFlags.join(" ") + " total");
5468
}
5569
}
5670
} catch (error) {

0 commit comments

Comments
 (0)