Skip to content

Commit 9138dac

Browse files
committed
fixed wc repeated file read and duplicate code
1 parent d01f00f commit 9138dac

File tree

1 file changed

+28
-36
lines changed
  • implement-shell-tools/wc

1 file changed

+28
-36
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 28 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,32 @@ async function wcJsImplement() {
1010
{
1111
commandLineArray.shift();
1212
}
13+
14+
function printOutput(lines,words,bytes,lable){
15+
switch (flags[0]) {
16+
case "-l":
17+
console.log(`${String(lines).padStart(4)} ${lable}`);
18+
break;
19+
case "-w":
20+
console.log(`${String(words).padStart(4)} ${lable}`);
21+
break;
22+
case "-c":
23+
console.log(`${String(bytes).padStart(4)} ${lable}`);
24+
break;
25+
default:
26+
console.log(
27+
`${String(lines).padStart(4)}${String(words).padStart(
28+
4
29+
)}${String(bytes).padStart(4)} ${lable}`
30+
);
31+
}
32+
}
33+
1334

1435
for(const file of commandLineArray){
15-
const fileContent=await fs.readFile(file , 'utf-8');
16-
const fileBuffer=await fs.readFile(file);
17-
bytes=fileBuffer.length;
36+
const buffer = await fs.readFile(file);
37+
const fileContent=buffer.toString("utf-8");
38+
bytes=buffer.length;
1839
TotalBytes += bytes;
1940

2041
const lines=fileContent.split(/\r?\n/);
@@ -33,41 +54,12 @@ async function wcJsImplement() {
3354
}
3455
}
3556
totalWords += wordsCount;
36-
37-
switch (flags[0]) {
38-
case "-l":
39-
console.log(`${String(linesCount).padStart(4)} ${file}`);
40-
break;
41-
case "-w":
42-
console.log(`${String(wordsCount).padStart(4)} ${file}`);
43-
break;
44-
case "-c":
45-
console.log(`${String(bytes).padStart(4)} ${file}`);
46-
break;
47-
default:
48-
console.log(`${String(linesCount).padStart(4)}${String(wordsCount).padStart(4)}${String(bytes).padStart(4)} ${file}`);
49-
}
50-
51-
57+
58+
printOutput(linesCount,wordsCount,bytes,file);
5259
}
60+
5361
if(commandLineArray.length>1){
54-
switch (flags[0]) {
55-
case "-l":
56-
console.log(`${String(totalLines).padStart(4)} total`);
57-
break;
58-
case "-w":
59-
console.log(`${String(totalWords).padStart(4)} total`);
60-
break;
61-
case "-c":
62-
console.log(`${String(TotalBytes).padStart(4)} total`);
63-
break;
64-
default :
65-
console.log(
66-
`${String(totalLines).padStart(4)}${String(totalWords).padStart(
67-
4
68-
)}${String(TotalBytes).padStart(4)} total`
69-
);
70-
}
62+
printOutput(totalLines, totalWords, TotalBytes, "total");
7163
}
7264

7365
}

0 commit comments

Comments
 (0)