-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathwc.js
More file actions
66 lines (57 loc) · 1.84 KB
/
wc.js
File metadata and controls
66 lines (57 loc) · 1.84 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
import { promises as fs } from "node:fs";
async function wcJsImplement() {
let totalLines=0,totalWords=0,TotalBytes=0;
let words,bytes;
const commandLineArray=process.argv.slice(2);
const flags = commandLineArray.filter((item) => item.startsWith("-"));
if(flags.length !==0 )
{
commandLineArray.shift();
}
function printOutput(lines,words,bytes,lable){
switch (flags[0]) {
case "-l":
console.log(`${String(lines).padStart(4)} ${lable}`);
break;
case "-w":
console.log(`${String(words).padStart(4)} ${lable}`);
break;
case "-c":
console.log(`${String(bytes).padStart(4)} ${lable}`);
break;
default:
console.log(
`${String(lines).padStart(4)}${String(words).padStart(
4
)}${String(bytes).padStart(4)} ${lable}`
);
}
}
for(const file of commandLineArray){
const buffer = await fs.readFile(file);
const fileContent=buffer.toString("utf-8");
bytes=buffer.length;
TotalBytes += bytes;
const lines=fileContent.split(/\r?\n/);
let linesCount,wordsCount=0;
//Calculate count of lines
if(lines[lines.length-1].trim()===""){
lines.pop();
linesCount=lines.length;
totalLines += linesCount;
}
//calculate count of words
for(const line of lines){
words=line.trim().split(/\s+/);
if (words[0].trim() !== ""){
wordsCount += words.length;
}
}
totalWords += wordsCount;
printOutput(linesCount,wordsCount,bytes,file);
}
if(commandLineArray.length>1){
printOutput(totalLines, totalWords, TotalBytes, "total");
}
}
wcJsImplement();