|
| 1 | +const fs = require("fs"); |
| 2 | + |
| 3 | +// get CLI arguments |
| 4 | +const args = process.argv.slice(2); |
| 5 | + |
| 6 | +// flags |
| 7 | +const showLines = args.includes("-l"); |
| 8 | +const showWords = args.includes("-w"); |
| 9 | +const showBytes = args.includes("-c"); |
| 10 | + |
| 11 | +// get files (remove flags) |
| 12 | +const files = args.filter((arg) => !arg.startsWith("-")); |
| 13 | + |
| 14 | +// helper functions |
| 15 | +function countLines(text) { |
| 16 | + return text.split("\n").length - 1; |
| 17 | +} |
| 18 | + |
| 19 | +function countWords(text) { |
| 20 | + return text.trim().split(/\s+/).filter(Boolean).length; |
| 21 | +} |
| 22 | + |
| 23 | +function countBytes(text) { |
| 24 | + return Buffer.byteLength(text, "utf8"); |
| 25 | +} |
| 26 | + |
| 27 | +// loop through files |
| 28 | +for (let i = 0; i < files.length; i++) { |
| 29 | + const file = files[i]; |
| 30 | + |
| 31 | + try { |
| 32 | + const content = fs.readFileSync(file, "utf8"); |
| 33 | + |
| 34 | + const lines = countLines(content); |
| 35 | + const words = countWords(content); |
| 36 | + const bytes = countBytes(content); |
| 37 | + |
| 38 | + let output = ""; |
| 39 | + |
| 40 | + // if no flag → show all |
| 41 | + if (!showLines && !showWords && !showBytes) { |
| 42 | + output = `${lines} ${words} ${bytes} ${file}`; |
| 43 | + } else { |
| 44 | + if (showLines) output += `${lines} `; |
| 45 | + if (showWords) output += `${words} `; |
| 46 | + if (showBytes) output += `${bytes} `; |
| 47 | + output += file; |
| 48 | + } |
| 49 | + |
| 50 | + console.log(output.trim()); |
| 51 | + } catch (err) { |
| 52 | + console.error(`wc: cannot open ${file}`); |
| 53 | + } |
| 54 | +} |
0 commit comments