1+ import { program } from "commander" ;
2+ import { promises as fs } from "node:fs" ;
3+ import process from "node:process" ;
4+
5+ program
6+ . name ( "wc command" )
7+ . description ( "Implementing 'wc' command" )
8+ . option ( "-l" , "show line count" )
9+ . option ( "-w" , "show word count" )
10+ . option ( "-c" , "show character count" )
11+ . argument ( "<paths...>" , "files to read" ) ;
12+
13+ program . parse ( ) ;
14+
15+ const paths = program . args ;
16+ const options = program . opts ( ) ;
17+
18+
19+ function formatCounts ( lines , words , chars , options ) {
20+ let result = "" ;
21+
22+ if ( options . l || options . w || options . c ) {
23+ if ( options . l ) result += `${ lines } L ` ;
24+ if ( options . w ) result += `${ words } W ` ;
25+ if ( options . c ) result += `${ chars } Char ` ;
26+ } else {
27+ result += `${ lines } L ${ words } W ${ chars } Char ` ;
28+ }
29+
30+ return result ;
31+ }
32+
33+ let totalLines = 0 ;
34+ let totalWords = 0 ;
35+ let totalChars = 0 ;
36+
37+ for ( const path of paths ) {
38+ const content = await fs . readFile ( path , "utf-8" ) ;
39+
40+ const lineCount = ( content . match ( / \n / g) || [ ] ) . length ;
41+ const wordCount = content . trim ( ) . split ( / \s + / ) . length ;
42+ const charCount = content . length ;
43+
44+ totalLines += lineCount ;
45+ totalWords += wordCount ;
46+ totalChars += charCount ;
47+
48+ const output = formatCounts ( lineCount , wordCount , charCount , options ) ;
49+
50+ console . log ( `${ output } ${ path } ` ) ;
51+ }
52+
53+ if ( paths . length > 1 ) {
54+ const totalOutput = formatCounts ( totalLines , totalWords , totalChars , options ) ;
55+
56+ console . log ( `${ totalOutput } total` ) ;
57+ }
0 commit comments