|
| 1 | +import { program } from "commander"; |
| 2 | + |
| 3 | +import { promises as fs } from "node:fs"; |
| 4 | + |
| 5 | +program |
| 6 | + .name("wc") |
| 7 | + .description("wc implementation") |
| 8 | + .argument("<paths...>", "the file path to process") |
| 9 | + .option("-l", "count lines") |
| 10 | + .option("-w", "count words") |
| 11 | + .option("-c", "count characters"); |
| 12 | + |
| 13 | +program.parse(); |
| 14 | + |
| 15 | +const paths = program.args; |
| 16 | +const options = program.opts(); |
| 17 | + |
| 18 | +const total = { |
| 19 | + linesCounter: 0, |
| 20 | + wordsCounter: 0, |
| 21 | + characterCounter: 0, |
| 22 | +}; |
| 23 | + |
| 24 | +try { |
| 25 | + for (const path of paths) { |
| 26 | + const content = await fs.readFile(path, "utf-8"); |
| 27 | + |
| 28 | + const linesCounter = content.split("\n").length - 1; |
| 29 | + const wordsCounter = content.trim().split(/\s+/).length; |
| 30 | + const characterCounter = content.length; |
| 31 | + |
| 32 | + total.linesCounter += linesCounter; |
| 33 | + total.wordsCounter += wordsCounter; |
| 34 | + total.characterCounter += characterCounter; |
| 35 | + |
| 36 | + let results = []; |
| 37 | + if (options.l) results.push(linesCounter); |
| 38 | + if (options.w) results.push(wordsCounter); |
| 39 | + if (options.c) results.push(characterCounter); |
| 40 | + |
| 41 | + if (!options.l && !options.w && !options.c) |
| 42 | + console.log( |
| 43 | + ` ${linesCounter} ${wordsCounter} ${characterCounter} ${path}`, |
| 44 | + ); |
| 45 | + else { |
| 46 | + console.log(results.join(" ") + " " + path); |
| 47 | + } |
| 48 | + } |
| 49 | + if (paths.length > 1) { |
| 50 | + if (!options.l && !options.w && !options.c) { |
| 51 | + console.log( |
| 52 | + ` ${total.linesCounter} ${total.wordsCounter} ${total.characterCounter} total`, |
| 53 | + ); |
| 54 | + } else { |
| 55 | + const totalWithFlags = []; |
| 56 | + if (options.l) totalWithFlags.push(total.linesCounter); |
| 57 | + if (options.w) totalWithFlags.push(total.wordsCounter); |
| 58 | + if (options.c) totalWithFlags.push(total.characterCounter); |
| 59 | + console.log(totalWithFlags.join(" ") + " total"); |
| 60 | + } |
| 61 | + } |
| 62 | +} catch (error) { |
| 63 | + console.error(error.message); |
| 64 | +} |
0 commit comments