-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
57 lines (42 loc) · 1.38 KB
/
wc.js
File metadata and controls
57 lines (42 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { program } from "commander";
import { promises as fs } from "node:fs";
import process from "node:process";
program
.name("wc command")
.description("Implementing 'wc' command")
.option("-l", "show line count")
.option("-w", "show word count")
.option("-c", "show character count")
.argument("<paths...>", "files to read");
program.parse();
const paths = program.args;
const options = program.opts();
function formatCounts(lines, words, chars, options) {
let result = "";
if (options.l || options.w || options.c) {
if (options.l) result += `${lines}L `;
if (options.w) result += `${words}W `;
if (options.c) result += `${chars}Char `;
} else {
result += `${lines}L ${words}W ${chars}Char `;
}
return result;
}
let totalLines = 0;
let totalWords = 0;
let totalChars = 0;
for (const path of paths) {
const content = await fs.readFile(path, "utf-8");
const lineCount = (content.match(/\n/g) || []).length;
const wordCount = content.trim().split(/\s+/).length;
const charCount = content.length;
totalLines += lineCount;
totalWords += wordCount;
totalChars += charCount;
const output = formatCounts(lineCount, wordCount, charCount, options);
console.log(`${output}${path}`);
}
if (paths.length > 1) {
const totalOutput = formatCounts(totalLines, totalWords, totalChars, options);
console.log(`${totalOutput}total`);
}