-
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathwc.mjs
More file actions
118 lines (91 loc) · 2.21 KB
/
Copy pathwc.mjs
File metadata and controls
118 lines (91 loc) · 2.21 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import process from "node:process";
import fs from "node:fs";
import { parseArgs } from "node:util";
const options = {
lines: {
type: "boolean",
short: "l",
},
words: {
type: "boolean",
short: "w",
},
bytes: {
type: "boolean",
short: "c",
},
};
const { values, positionals } = parseArgs({
options,
allowPositionals: true,
});
if (positionals.length === 0) {
process.stderr.write("Please provide a file.\n");
process.exit(1);
}
const fileCounts = [];
for (const path of positionals) {
fileCounts.push(countFile(path));
}
const totalCounts = {
lineCount: 0,
wordCount: 0,
byteCount: 0,
};
for (const file of fileCounts) {
totalCounts.lineCount += file.lineCount;
totalCounts.wordCount += file.wordCount;
totalCounts.byteCount += file.byteCount;
}
// output formatting
const largestByteCount =
fileCounts.length > 1 ? totalCounts.byteCount : fileCounts[0].byteCount;
const width = String(largestByteCount).length;
for (const file of fileCounts) {
const formattedCounts = formatCounts(file, width);
process.stdout.write(`${formattedCounts} ${file.path}\n`);
}
if (fileCounts.length > 1) {
const formattedTotals = formatCounts(totalCounts, width);
process.stdout.write(`${formattedTotals} total\n`);
}
function countFile(path) {
const content = fs.readFileSync(path, "utf-8");
const lineCount = [...content].filter((char) => char === "\n").length;
const trimmedContent = content.trim();
const wordCount =
trimmedContent === "" ? 0 : trimmedContent.split(/\s+/).length;
const byteCount = Buffer.byteLength(content);
return {
lineCount,
wordCount,
byteCount,
path,
};
}
function getSelectedCounts(lineCount, wordCount, byteCount) {
const selectedCounts = [];
if (values.lines) {
selectedCounts.push(lineCount);
}
if (values.words) {
selectedCounts.push(wordCount);
}
if (values.bytes) {
selectedCounts.push(byteCount);
}
if (selectedCounts.length === 0) {
selectedCounts.push(lineCount, wordCount, byteCount);
}
return selectedCounts;
}
function formatCounts(counts, width) {
const selectedCounts = getSelectedCounts(
counts.lineCount,
counts.wordCount,
counts.byteCount,
);
return selectedCounts
.map((count) => String(count).padStart(width))
.join(" ");
}