-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathwc.js
More file actions
91 lines (84 loc) · 2.48 KB
/
wc.js
File metadata and controls
91 lines (84 loc) · 2.48 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
import process from "node:process";
import { promises as fs } from "node:fs";
const argv = process.argv.slice(2, process.argv.length);
let flag = '';
const paths = [];
let dir = '';
let ending = '';
for (let i = 0; i < argv.length; i++) {
if (argv[i][0] == "-") {
flag = argv[i];
} else {
paths.push(argv[i]);
}
}
if (paths.length > 0) {
dir = paths[0].slice(0, paths[0].indexOf("/"));
ending = paths[0].slice(paths[0].indexOf("/") + 1);
};
const files = await resolveQuery(paths, dir, ending);
await logFilesInfo(files, flag);
async function resolveQuery(paths, dir, ending) {
let files = [];
if (paths.length > 1) {
files = await fs.readdir(dir);
} else {
files = [ending];
}
return files;
}
async function logFilesInfo(files, flag) {
let totalLines = 0;
let totalWords = 0;
let totalBytes = 0;
let totalOutput = '';
for (const fileName of files) {
let fileOutput = '';
let filePath = dir + "/" + fileName;
let file = await fs.readFile(filePath, "utf-8");
let linesNum = countLinesInString(file);
let wordsNum = countWordsInString(file);
let bytes = file.length;
totalLines += linesNum;
totalWords += wordsNum;
totalBytes += bytes;
if (flag == "-l") {
fileOutput = linesNum + " " + filePath;
} else if (flag == "-w") {
fileOutput = wordsNum + " " + filePath;
} else if (flag == '-c') {
fileOutput = bytes + " " + filePath;
} else {
fileOutput = linesNum + " " + wordsNum + " " + bytes + " " + filePath;
}
console.log(fileOutput);
}
if (files.length > 1) {
if (flag == "-l") {
totalOutput = totalLines + " total";
} else if (flag == "-w") {
totalOutput = totalWords + " total";
} else if (flag == '-c') {
totalOutput = totalBytes + " total";
} else {
totalOutput = totalLines + " " + totalWords + " " + totalBytes + " total";
}
console.log(totalOutput);
}
}
function countLinesInString(str) {
let lines = str.split('\n');
let linesNum = lines.length;
if (lines[lines.length - 1] == '') {
linesNum--;
}
return linesNum;
}
function countWordsInString(str) {
let words = str.replace(/\n/g, ' ').split(' ');
words = words.filter((word) => {
return (word != '')
});
let wordsNum = words.length;
return wordsNum;
}