Skip to content

Commit c6a7649

Browse files
committed
feat(wc): implement wc command for word, line, and byte counting
1 parent 4abcb92 commit c6a7649

3 files changed

Lines changed: 66 additions & 0 deletions

File tree

implement-shell-tools/wc/package-lock.json

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"type": "module",
3+
"dependencies": {
4+
"commander": "^14.0.3"
5+
}
6+
}

implement-shell-tools/wc/wc.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { program } from "commander";
2+
import * as fs from "node:fs/promises";
3+
4+
//*** TODO ***
5+
// * Format results
6+
// * Add optional flags
7+
8+
program
9+
.name("wc")
10+
.description("word, line and byte count")
11+
.argument("<paths...>", "The file path(s) to process");
12+
13+
program.parse();
14+
15+
try {
16+
const filePaths = program.args;
17+
const results = {};
18+
19+
for (const filePath of filePaths) {
20+
const file = await fs.open(filePath);
21+
const stats = await fs.stat(filePath);
22+
23+
const count = { lines: 0, words: 0, bytes: stats.size };
24+
25+
try {
26+
for await (const line of file.readLines()) {
27+
count.lines++;
28+
count.words += line.trim().split(/\s+/).length;
29+
}
30+
} finally {
31+
await file.close();
32+
}
33+
34+
results[filePath] = count;
35+
}
36+
console.log(results);
37+
} catch (err) {
38+
console.error(err.message);
39+
}

0 commit comments

Comments
 (0)