Skip to content

Commit 812b7fb

Browse files
Basic output structure for wc complete
1 parent 836f423 commit 812b7fb

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
program
5+
.name("node-cat")
6+
.description("A Node.js implementation of the Unix cat command")
7+
.option("-n, --number", "Number all output lines")
8+
.option(
9+
"-b, --numberNonBlank",
10+
"Numbers only non-empty lines. Overrides -n option"
11+
)
12+
.argument("<path...>", "The file path to process");
13+
14+
program.parse();
15+
16+
const paths = program.args;
17+
const { number, numberNonBlank } = program.opts();
18+
19+
// --- Read files and sizes ---
20+
let content = "";
21+
let fileSize;
22+
23+
for (const path of paths) {
24+
content = await fs.readFile(path, "utf-8");
25+
if (content.endsWith("\n")) {
26+
content = content.slice(0, -1);
27+
}
28+
fileSize = await fs.stat(path);
29+
console.log(
30+
getLineCount(content),
31+
getWordCount(content),
32+
fileSize.size,
33+
path
34+
);
35+
}
36+
37+
function getWordCount(text) {
38+
let words, lines;
39+
40+
lines = text.split("\n");
41+
// console.log(lines);
42+
words = lines.flatMap((line) => line.split(" "));
43+
44+
return words.filter((word) => word.length > 0).length;
45+
}
46+
47+
function getLineCount(text) {
48+
let lines;
49+
return (lines = text.split("\n").length);
50+
}
51+
52+
// 1 4 20 sample-files/1.txt
53+
// 1 7 39 sample-files/2.txt
54+
// 5 24 125 sample-files/3.txt
55+
// 7 35 184 total

0 commit comments

Comments
 (0)