Skip to content

Commit ae796c4

Browse files
committed
completed wc exercises
1 parent 6fe53af commit ae796c4

1 file changed

Lines changed: 21 additions & 24 deletions

File tree

implement-shell-tools/wc/customWc.js

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ function padStartNumbers(...args) {
3030
return numberStringArray.join("");
3131
}
3232

33+
const totalRowNumbers = [];
34+
3335
let totalOfLines = 0;
3436
let totalOfWords = 0;
3537
let totalOfCharacters = 0;
@@ -40,44 +42,39 @@ for (let path of pathArray) {
4042
let numberOfCharacters = 0;
4143

4244
const file = await fs.readFile(path, "utf-8");
43-
numberOfCharacters = file.length;
4445
numberOfLines = file.split("\n").length - 1;
4546
const words = file.match(/\S+/g);
4647
numberOfWords = words ? words.length : 0;
48+
numberOfCharacters = file.length;
4749

48-
if (pathArray.length > 1) {
49-
if (options.lines) {
50-
console.log(`${padStartNumbers(numberOfLines)} ${path}`);
51-
}
52-
if (options.words) {
53-
console.log(`${padStartNumbers(numberOfWords)} ${path}`);
54-
}
55-
if (options.characters) {
56-
console.log(`${padStartNumbers(numberOfCharacters)} ${path}`);
57-
}
58-
} else if (options.lines) {
59-
console.log(`${numberOfLines} ${path}`);
60-
} else if (options.words) {
61-
console.log(`${numberOfWords} ${path}`);
62-
} else if (options.characters) {
63-
console.log(`${numberOfCharacters} ${path}`);
64-
} else {
50+
const rowNumbers = [];
51+
52+
if (options.lines) rowNumbers.push(numberOfLines);
53+
if (options.words) rowNumbers.push(numberOfWords);
54+
if (options.characters) rowNumbers.push(numberOfCharacters);
55+
56+
if (rowNumbers.length === 0) {
6557
console.log(
6658
`${padStartNumbers(numberOfLines, numberOfWords, numberOfCharacters)} ${path}`,
6759
);
60+
} else {
61+
if (pathArray.length === 1 && rowNumbers.length === 1) {
62+
console.log(`${rowNumbers[0]} ${path}`);
63+
} else {
64+
console.log(`${padStartNumbers(...rowNumbers)} ${path}`);
65+
}
6866
}
6967
totalOfLines += numberOfLines;
7068
totalOfWords += numberOfWords;
7169
totalOfCharacters += numberOfCharacters;
7270
}
7371

7472
if (pathArray.length > 1) {
75-
if (options.lines) {
76-
console.log(`${padStartNumbers(totalOfLines)} total`);
77-
} else if (options.words) {
78-
console.log(`${padStartNumbers(totalOfWords)} total`);
79-
} else if (options.characters) {
80-
console.log(`${padStartNumbers(totalOfCharacters)} total`);
73+
if (options.lines) totalRowNumbers.push(totalOfLines);
74+
if (options.words) totalRowNumbers.push(totalOfWords);
75+
if (options.characters) totalRowNumbers.push(totalOfCharacters);
76+
if (totalRowNumbers.length > 0) {
77+
console.log(`${padStartNumbers(...totalRowNumbers)} total`);
8178
} else {
8279
console.log(
8380
`${padStartNumbers(totalOfLines, totalOfWords, totalOfCharacters)} total`,

0 commit comments

Comments
 (0)