Skip to content

Commit 1a80d5b

Browse files
committed
prints lwc for one or more files
1 parent 3c8e345 commit 1a80d5b

1 file changed

Lines changed: 34 additions & 19 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,13 @@ program
88
.option("-w")
99
.option("-c")
1010
.option("-l")
11-
.argument("<files...>", "file to process");
11+
.argument("<files...>", "files to process");
1212

1313
program.parse();
1414

1515
const options = program.opts();
1616
const paths = program.args;
1717

18-
console.log(options);
19-
console.log(paths);
20-
2118
// if no -lwc flags are supplied, wc prints
2219
// lines, words, bytes of each file
2320
// whereas if any flags are supplied only those
@@ -26,25 +23,43 @@ if (Object.keys(options).length === 0) {
2623
options.l = options.w = options.c = true;
2724
}
2825

29-
/*
30-
for each path:
31-
if path is not a directory, show error message
32-
else:
33-
create a temporary array
34-
if l in options:
35-
push line count to temp arr
36-
if w in options:
37-
push word count into temp arr
38-
if c in options:
39-
push byte count into data
40-
41-
join the array with path and print
42-
*/
26+
// keeps track of total values for each of the data
27+
// incrementally updated in the loop below
28+
const totals = { l: 0, w: 0, c: 0 };
4329

4430
for (const path of paths) {
4531
if (fs.statSync(path).isDirectory()) {
4632
console.log(`wc: ${path}: read: Is a directory`);
4733
} else {
48-
console.log(`${path} is a file`);
34+
let outputStr = "";
35+
const file = fs.readFileSync(path, "utf-8");
36+
if (options.l) {
37+
const lines = file.split("\n");
38+
// exclude trailing empty line from count
39+
if (lines.at(-1) === "") {
40+
lines.pop();
41+
}
42+
const lineCount = lines.length;
43+
totals.l += lineCount;
44+
outputStr += `\t${lineCount}`;
45+
}
46+
47+
if (options.w) {
48+
// real wc splits not just on " ", but on white spaces more generally
49+
const words = file.split(/\s+/).filter(Boolean);
50+
const wordCount = words.length;
51+
totals.w += wordCount;
52+
outputStr += `\t${wordCount}`;
53+
}
54+
55+
if (options.c) {
56+
file.size;
57+
const byteCount = fs.statSync(path).size;
58+
totals.c += byteCount;
59+
outputStr += `\t${byteCount}`;
60+
}
61+
62+
outputStr += ` ${path}`;
63+
console.log(outputStr);
4964
}
5065
}

0 commit comments

Comments
 (0)