-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
69 lines (57 loc) · 2.33 KB
/
wc.js
File metadata and controls
69 lines (57 loc) · 2.33 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
import process from "node:process";
import { promises as fs } from "node:fs";
import { Command } from "commander";
const program = new Command();
program
.name("wc")
.description("A simple node implementation of the word count utility")
.argument("[files...]", "Files to process")
.option("-l, --lines", "print the newline counts")
.option("-w, --words", "print the word counts")
.option("-c, --bytes", "print the byte counts")
.action(async (filePaths, options) => {
const noFlagsProvided = !options.lines && !options.words && !options.bytes;
const shouldShowAllStats = noFlagsProvided;
const allFileStats = [];
for (const filePath of filePaths) {
try {
const fileStats = await calculateFileStats(filePath);
allFileStats.push(fileStats);
printFormattedReport(fileStats, options, shouldShowAllStats);
} catch (error) {
console.error(`wc: ${filePath}: No such file or directory`);
process.exitCode = 1;
}
}
if (allFileStats.length > 1) {
const grandTotals = {
lineCount: allFileStats.reduce((sum, stat) => sum + stat.lineCount, 0),
wordCount: allFileStats.reduce((sum, stat) => sum + stat.wordCount, 0),
byteCount: allFileStats.reduce((sum, stat) => sum + stat.byteCount, 0),
displayName: "total"
};
printFormattedReport(grandTotals, options, shouldShowAllStats);
}
});
async function calculateFileStats(filePath) {
const fileBuffer = await fs.readFile(filePath);
const fileContent = fileBuffer.toString();
const lines = fileContent.split("\n").length - 1;
const words = fileContent.split(/\s+/).filter(word => word.length > 0).length;
const bytes = fileBuffer.length;
return {
lineCount: lines,
wordCount: words,
byteCount: bytes,
displayName: filePath
};
}
function printFormattedReport(stats, options, shouldShowAllStats) {
const outputColumns = [];
const formatColumn = (count) => String(count).padStart(4);
if (shouldShowAllStats || options.lines) outputColumns.push(formatColumn(stats.lineCount));
if (shouldShowAllStats || options.words) outputColumns.push(formatColumn(stats.wordCount));
if (shouldShowAllStats || options.bytes) outputColumns.push(formatColumn(stats.byteCount));
console.log(`${outputColumns.join("")} ${stats.displayName}`);
}
program.parse(process.argv);