-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathMyWc.js
More file actions
68 lines (58 loc) · 1.66 KB
/
MyWc.js
File metadata and controls
68 lines (58 loc) · 1.66 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
58
59
60
61
62
63
64
65
66
67
68
import { program } from "commander";
import { promises as fs } from "node:fs";
import process from "node:process";
program
.name("myLs")
.description("my ls clone")
.option("-l", "line count")
.option("-w", "words count")
.option("-c", "character count")
.option("-s", "character count without spaces")
.argument("[paths...]", "file or directory paths");
program.parse();
const opts = program.opts();
let files = program.args;
if (files.length === 0) {
files = ["."];
}
let totalLines = 0;
let totalWords = 0;
if (opts.l) {
for (const file of files) {
const content = await fs.readFile(file, "utf-8");
console.log(content);
const lineCount = content.split("\n").length;
totalLines += lineCount;
}
console.log("Lines:", totalLines);
}
if (opts.w) {
for (const file of files) {
const content = await fs.readFile(file, "utf-8");
console.log(content);
const wordCount = content.trim().split(/\s+/).length;
totalWords += wordCount;
}
console.log("Total words:", totalWords);
}
if (opts.c) {
let totalChars = 0;
for (const file of files) {
const content = await fs.readFile(file, "utf-8");
totalChars += content.trim().length;
// const charList = content.trim().split(/\s+/);
// for (const char of charList) {
// totalChars += char.length;
// }
}
console.log("Total characters:", totalChars);
}
if (opts.s) {
let totalCharsNoSpaces = 0;
for (const file of files) {
const content = await fs.readFile(file, "utf-8");
const withoutSpaces = content.replace(/\s/g, "");
totalCharsNoSpaces += withoutSpaces.length;
}
console.log("Total characters without spaces:", totalCharsNoSpaces);
}