Skip to content

Commit daac5ec

Browse files
committed
complete wc exercise
1 parent 34fe1d0 commit daac5ec

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

  • implement-shell-tools/wc

implement-shell-tools/wc/wc.js

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!/usr/bin/env node
2+
3+
const fs = require('fs');
4+
const path = require('path');
5+
6+
function countFile(filePath, options) {
7+
try {
8+
const data = fs.readFileSync(filePath, 'utf8');
9+
10+
const lines = data.split('\n').length;
11+
const words = data.split(/\s+/).filter(Boolean).length;
12+
const bytes = Buffer.byteLength(data, 'utf8');
13+
14+
if (options.lines) {
15+
console.log(`${lines}\t${filePath}`);
16+
} else if (options.words) {
17+
console.log(`${words}\t${filePath}`);
18+
} else if (options.bytes) {
19+
console.log(`${bytes}\t${filePath}`);
20+
} else {
21+
console.log(`${lines}\t${words}\t${bytes}\t${filePath}`);
22+
}
23+
} catch (err) {
24+
console.error(`wc: ${filePath}: No such file or directory`);
25+
}
26+
}
27+
28+
function main() {
29+
const args = process.argv.slice(2);
30+
const options = {
31+
lines: false,
32+
words: false,
33+
bytes: false,
34+
};
35+
36+
const files = [];
37+
38+
args.forEach((arg) => {
39+
if (arg === '-l') {
40+
options.lines = true;
41+
} else if (arg === '-w') {
42+
options.words = true;
43+
} else if (arg === '-c') {
44+
options.bytes = true;
45+
} else {
46+
files.push(arg);
47+
}
48+
});
49+
50+
if (files.length === 0) {
51+
console.error('Usage: wc [-l | -w | -c] <file>...');
52+
process.exit(1);
53+
}
54+
55+
files.forEach((file) => {
56+
const filePath = path.resolve(file);
57+
countFile(filePath, options);
58+
});
59+
}
60+
61+
main();

0 commit comments

Comments
 (0)