Skip to content

Commit bf0321e

Browse files
committed
wc_implementation
1 parent f6d926d commit bf0321e

3 files changed

Lines changed: 88 additions & 0 deletions

File tree

implement-shell-tools/wc/package-lock.json

Lines changed: 21 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "module",
3+
"dependencies": {
4+
"commander": "^15.0.0"
5+
}
6+
}
7+

implement-shell-tools/wc/wc.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import process from "node:process";
2+
import {program} from "commander";
3+
import {promises as fs} from "node:fs";
4+
5+
program
6+
.name("WC clone")
7+
.description("Counting each words in a given file")
8+
.argument("<files...>","one or more files to count the words")
9+
.action(async (files)=>{
10+
let totalLines = 0;
11+
let totalWords = 0;
12+
let totalBytes = 0;
13+
14+
for (const file of files){
15+
try {
16+
const content = await fs.readFile(file,"utf-8");
17+
const size = await fs.readFile(file);
18+
19+
const lineCount = content.split("\n").length-1;
20+
21+
const wordCount = content.trim() === "" ? 0 : content.trim().split(/\s+/).length;
22+
23+
const byteCount = size.length;
24+
25+
totalLines += lineCount;
26+
totalWords += wordCount;
27+
totalBytes += byteCount;
28+
29+
printCounts({lineCount,wordCount,byteCount,label:file,});
30+
}
31+
32+
catch (err){
33+
console.error("No such file or directory");
34+
process.exit(1);
35+
}
36+
}
37+
38+
if (files.length>1)
39+
{
40+
printCounts({lineCount:totalLines,
41+
wordCount:totalWords,
42+
byteCount:totalBytes,
43+
label:"Total",
44+
})
45+
}
46+
47+
});
48+
49+
function printCounts({lineCount,wordCount,byteCount,label})
50+
{
51+
let output = "";
52+
53+
output += lineCount.toString().padStart(7, " ");
54+
output += wordCount.toString().padStart(7," ");
55+
output += byteCount.toString().padStart(7," ");
56+
57+
console.log(`${output} ${label}`);
58+
}
59+
60+
program.parse(process.argv);

0 commit comments

Comments
 (0)