77 . description (
88 "The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input"
99 )
10+ . option ( "-l, --lines" , "count lines only" )
11+ . option ( "-w, --words" , "count words only" )
12+ . option ( "-c, --bytes" , "count bytes only" )
1013 . argument ( "<path...>" , "The file paths to process" ) ;
1114
1215//interpret the program
@@ -15,7 +18,25 @@ program.parse();
1518//initialise totals
1619let totalLines = 0 ;
1720let totalWords = 0 ;
18- let totalCharacters = 0 ;
21+ let totalBytes = 0 ;
22+
23+ //check for flags
24+ const hasLineFlag = program . opts ( ) . lines ;
25+ const hasWordFlag = program . opts ( ) . words ;
26+ const hasBytesFlag = program . opts ( ) . bytes ;
27+
28+ // create output format function to avoid repetition
29+ function formatOutput ( lines , words , bytes , path ) {
30+ if ( hasLineFlag ) {
31+ console . log ( `${ lines } ${ path } ` ) ;
32+ } else if ( hasWordFlag ) {
33+ console . log ( `${ words } ${ path } ` ) ;
34+ } else if ( hasBytesFlag ) {
35+ console . log ( `${ bytes } ${ path } ` ) ;
36+ } else {
37+ console . log ( `${ lines } ${ words } ${ bytes } ${ path } ` ) ;
38+ }
39+ }
1940
2041//process each file
2142
@@ -29,17 +50,17 @@ for (const path of program.args) {
2950 //count words (split by any whitespace)
3051 const words = content . split ( / \s + / ) . filter ( ( word ) => word . length > 0 ) . length ;
3152
32- //count character
33- const characters = content . length ;
53+ //count bytes correctly especially important for non-ASCII characters
54+ const bytes = Buffer . byteLength ( content , "utf-8" ) ;
3455
3556 //Add to totals
3657 totalLines += lines ;
3758 totalWords += words ;
38- totalCharacters += characters ;
59+ totalBytes += bytes ;
3960
40- console . log ( ` ${ lines } ${ words } ${ characters } ${ path } ` ) ;
61+ formatOutput ( lines , words , bytes , path ) ;
4162}
4263
4364if ( program . args . length > 1 ) {
44- console . log ( ` ${ totalLines } ${ totalWords } ${ totalCharacters } total` ) ;
65+ formatOutput ( totalLines , totalWords , totalBytes , " total" ) ;
4566}
0 commit comments