Skip to content

Commit b8b055e

Browse files
committed
feat: add -l option to wc implementation
1 parent 383f3a6 commit b8b055e

File tree

1 file changed

+41
-20
lines changed
  • implement-shell-tools/wc

1 file changed

+41
-20
lines changed

implement-shell-tools/wc/wc.mjs

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,58 @@
11
import { program } from "commander";
2-
import { error } from "node:console";
3-
import { promises as fs, link } from "node:fs";
2+
3+
import { promises as fs} from "node:fs";
44

55
program
66
.name("wc")
77
.description("wc implementation")
8-
.argument("<paths...>", "the file path to process");
8+
.argument("<paths...>", "the file path to process")
9+
.option("-l", "count how many lines");
910
program.parse();
1011

12+
1113
const paths = program.args;
14+
15+
if (paths.length === 0) {
16+
console.error("Expected at least one argument (a path)");
17+
process.exit(1);
18+
}
19+
20+
21+
const options = program.opts();
1222
const total = {
1323
linesCounter: 0,
1424
wordsCounter: 0,
1525
characterCounter: 0,
1626
};
17-
try{
18-
for (const path of paths) {
19-
const content = await fs.readFile(path, "utf-8");
27+
try {
28+
for (const path of paths) {
29+
const content = await fs.readFile(path, "utf-8");
2030

21-
const linesCounter = content.split("\n").length - 1;
22-
const wordsCounter = content.trim().split(/\s+/).length;
23-
const characterCounter = content.length;
31+
const linesCounter = content.split("\n").length - 1;
32+
const wordsCounter = content.trim().split(/\s+/).length;
33+
const characterCounter = content.length;
2434

25-
total.linesCounter += linesCounter;
26-
total.wordsCounter += wordsCounter;
27-
total.characterCounter += characterCounter;
35+
total.linesCounter += linesCounter;
36+
total.wordsCounter += wordsCounter;
37+
total.characterCounter += characterCounter;
2838

29-
console.log(` ${linesCounter} ${wordsCounter} ${characterCounter} ${path}`);
39+
if (options.l) {
40+
console.log(`${linesCounter} ${path}`);
41+
} else {
42+
console.log(
43+
` ${linesCounter} ${wordsCounter} ${characterCounter} ${path}`,
44+
);
45+
}
46+
}
47+
if (paths.length > 1) {
48+
if (options.l) {
49+
console.log(`${total.linesCounter} total`);
50+
} else {
51+
console.log(
52+
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
53+
);
54+
}
55+
}
56+
} catch (error) {
57+
console.error(error.message);
3058
}
31-
if (paths.length > 1)
32-
console.log(
33-
` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`,
34-
);
35-
}catch(error){
36-
console.log(error.message);
37-
}

0 commit comments

Comments
 (0)