Skip to content

Commit 1527ac2

Browse files
committed
node implementation for wc
1 parent a8ed8dc commit 1527ac2

File tree

1 file changed

+61
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+61
-0
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
//configuring
5+
program
6+
.name("wc")
7+
.description("Print newline, word, and byte counts for each file")
8+
.option("-l, --lines", "Print the newline counts")
9+
.option("-w, --words", "Print the word counts")
10+
.option("-c, --bytes", "Print the byte counts")
11+
.argument("<files...>", "File paths to process")
12+
//Interpret the program
13+
program.parse()
14+
const options = program.opts()
15+
const files = program.args //Interpreting parsed data
16+
17+
18+
//helper function to calculate all counts
19+
async function getCounts(file){
20+
const content = await fs.readFile(file, "utf-8");
21+
const lineCount = content.split("\n").length -1;//split("\n") returns one more element than the actual number so length-1,
22+
const wordCount = content.trim().split(/\s+/).length;
23+
const byteCount = Buffer.byteLength(content, "utf-8"); //Calculate how many bytes the string uses in UTF-8 (important because some characters use more than 1 byte)
24+
return { lineCount, wordCount, byteCount };
25+
}
26+
//initiating totals
27+
let totalLines = 0;
28+
let totalWords = 0;
29+
let totalBytes = 0;
30+
31+
for (const file of files) {
32+
const { lineCount, wordCount, byteCount } = await getCounts(file);
33+
34+
totalLines += lineCount;
35+
totalWords += wordCount;
36+
totalBytes += byteCount;
37+
38+
let output = "";
39+
if (options.lines) output += `${lineCount} `;
40+
if (options.words) output += `${wordCount} `;
41+
if (options.bytes) output += `${byteCount} `;
42+
if (!options.lines && !options.words && !options.bytes) {
43+
output += `${lineCount} ${wordCount} ${byteCount} `;
44+
}
45+
output += file;
46+
console.log(output);
47+
}
48+
49+
50+
//Print totals if multiple files
51+
if (files.length > 1) {
52+
let totalOutput = "";
53+
if (options.lines) totalOutput += `${totalLines} `;
54+
if (options.words) totalOutput += `${totalWords} `;
55+
if (options.bytes) totalOutput += `${totalBytes} `;
56+
if (!options.lines && !options.words && !options.bytes) {
57+
totalOutput += `${totalLines} ${totalWords} ${totalBytes} `;
58+
}
59+
totalOutput += "total";
60+
console.log(totalOutput);
61+
}

0 commit comments

Comments
 (0)