-
-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathwc.js
More file actions
54 lines (42 loc) · 1.22 KB
/
wc.js
File metadata and controls
54 lines (42 loc) · 1.22 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
const fs = require("fs");
// get CLI arguments
const args = process.argv.slice(2);
// flags
const showLines = args.includes("-l");
const showWords = args.includes("-w");
const showBytes = args.includes("-c");
// get files (remove flags)
const files = args.filter((arg) => !arg.startsWith("-"));
// helper functions
function countLines(text) {
return text.split("\n").length - 1;
}
function countWords(text) {
return text.trim().split(/\s+/).filter(Boolean).length;
}
function countBytes(text) {
return Buffer.byteLength(text, "utf8");
}
// loop through files
for (let i = 0; i < files.length; i++) {
const file = files[i];
try {
const content = fs.readFileSync(file, "utf8");
const lines = countLines(content);
const words = countWords(content);
const bytes = countBytes(content);
let output = "";
// if no flag → show all
if (!showLines && !showWords && !showBytes) {
output = `${lines} ${words} ${bytes} ${file}`;
} else {
if (showLines) output += `${lines} `;
if (showWords) output += `${words} `;
if (showBytes) output += `${bytes} `;
output += file;
}
console.log(output.trim());
} catch (err) {
console.error(`wc: cannot open ${file}`);
}
}