66 . name ( "wc" )
77 . description ( "wc implementation" )
88 . argument ( "<paths...>" , "the file path to process" )
9- . option ( "-l" , "count how many lines" ) ;
9+ . option ( "-l" , "count lines" )
10+ . option ( "-w" , "count words" )
11+ . option ( "-c" , "count characters" ) ;
12+
1013program . parse ( ) ;
1114
1215
@@ -17,13 +20,15 @@ if (paths.length === 0) {
1720 process . exit ( 1 ) ;
1821}
1922
20-
2123const options = program . opts ( ) ;
24+
2225const total = {
2326 linesCounter : 0 ,
2427 wordsCounter : 0 ,
2528 characterCounter : 0 ,
2629} ;
30+
31+
2732try {
2833 for ( const path of paths ) {
2934 const content = await fs . readFile ( path , "utf-8" ) ;
@@ -36,21 +41,30 @@ try {
3641 total . wordsCounter += wordsCounter ;
3742 total . characterCounter += characterCounter ;
3843
39- if ( options . l ) {
40- console . log ( `${ linesCounter } ${ path } ` ) ;
41- } else {
44+ let results = [ ] ;
45+ if ( options . l ) results . push ( linesCounter ) ;
46+ if ( options . w ) results . push ( wordsCounter ) ;
47+ if ( options . c ) results . push ( characterCounter ) ;
48+
49+ if ( ! options . l && ! options . w && ! options . c )
4250 console . log (
4351 ` ${ linesCounter } ${ wordsCounter } ${ characterCounter } ${ path } ` ,
4452 ) ;
53+ else {
54+ console . log ( results . join ( " " ) + " " + path ) ;
4555 }
4656 }
4757 if ( paths . length > 1 ) {
48- if ( options . l ) {
49- console . log ( `${ total . linesCounter } total` ) ;
50- } else {
58+ if ( ! options . l && ! options . w && ! options . c ) {
5159 console . log (
5260 ` ${ total . linesCounter } ${ total . wordsCounter } ${ total . characterCounter } total` ,
5361 ) ;
62+ } else {
63+ const totalWithFlags = [ ] ;
64+ if ( options . l ) totalWithFlags . push ( total . linesCounter ) ;
65+ if ( options . w ) totalWithFlags . push ( total . wordsCounter ) ;
66+ if ( options . c ) totalWithFlags . push ( total . characterCounter ) ;
67+ console . log ( totalWithFlags . join ( " " ) + " total" ) ;
5468 }
5569 }
5670} catch ( error ) {
0 commit comments