-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathmy-wc.js
More file actions
executable file
·83 lines (61 loc) · 1.76 KB
/
Copy pathmy-wc.js
File metadata and controls
executable file
·83 lines (61 loc) · 1.76 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
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env node
const fs = require("node:fs");
function countFile(filePath) {
const stats = fs.statSync(filePath);
if (!stats.isFile()) {
console.warn(`${filePath} is not a file, skipping`);
return null;
}
const content = fs.readFileSync(filePath, "utf8");
const lines = content.split("\n").length - 1;
const words = content.trim() ? content.trim().split(/\s+/).length : 0;
const chars = Buffer.byteLength(content, "utf8");
return { lines, words, chars };
}
function main() {
const args = process.argv.slice(2);
let flags = [];
let files = [];
// 1 Parse args
for (const arg of args) {
if (arg === "-l" || arg === "-w" || arg === "-c") {
flags.push(arg);
} else {
files.push(arg);
}
}
//2 Helper function that decides what to print
function formatOutput(counts, files) {
const parts = [];
// if no flags show everything
const showAll = flags.length === 0;
if (showAll || flags.includes("-l"))parts.push(counts.lines);
if (showAll || flags.includes("-w"))parts.push(counts.words);
if (showAll || flags.includes("-c"))parts.push(counts.chars);
parts.push(files);
return parts.join(" ");
}
// 3 totals
let totalLines = 0;
let totalWords = 0;
let totalChars = 0;
// 4 per-file output
for (const file of files) {
const counts = countFile(file);
if (!counts) continue;
totalLines += counts.lines;
totalWords += counts.words;
totalChars += counts.chars;
console.log(formatOutput(counts, files));
}
// 5 Total output (only if multiple files)
if (files.length > 1) {
const totalCounts = {
lines: totalLines,
words: totalWords,
chars: totalChars,
};
console.log(formatOutput(totalCounts,"total"));
}
}
main();