@@ -14,44 +14,42 @@ program.parse();
1414const options = program . opts ( ) ;
1515const filePaths = program . args ;
1616
17+ function formatCounts ( lines , words , chars , options ) {
18+ let result = "" ;
19+
20+ if ( options . l || options . w || options . c ) {
21+ if ( options . l ) result += `${ lines } ` ;
22+ if ( options . w ) result += `${ words } ` ;
23+ if ( options . c ) result += `${ chars } ` ;
24+ } else {
25+ result += `${ lines } ${ words } ${ chars } ` ;
26+ }
27+
28+ return result ;
29+ }
30+
1731let totalLines = 0 ;
1832let totalWords = 0 ;
1933let totalChars = 0 ;
2034
2135for ( const filePath of filePaths ) {
2236 const content = await fs . readFile ( filePath , "utf-8" ) ;
2337
24- const lineCount = content . split ( "\n" ) . length ;
38+ const lineCount = ( content . match ( / \n / g ) || [ ] ) . length ;
2539 const wordCount = content . trim ( ) . split ( / \s + / ) . length ;
2640 const charCount = content . length ;
2741
2842 totalLines += lineCount ;
2943 totalWords += wordCount ;
3044 totalChars += charCount ;
3145
32- let output = "" ;
33-
34- if ( options . l || options . w || options . c ) {
35- if ( options . l ) output += `${ lineCount } ` ;
36- if ( options . w ) output += `${ wordCount } ` ;
37- if ( options . c ) output += `${ charCount } ` ;
38- } else {
39- output += `${ lineCount } ${ wordCount } ${ charCount } ` ;
40- }
46+ const output = formatCounts ( lineCount , wordCount , charCount , options ) ;
4147
4248 console . log ( `${ output } ${ filePath } ` ) ;
4349}
4450
4551if ( filePaths . length > 1 ) {
46- let totalOutput = "" ;
47-
48- if ( options . l || options . w || options . c ) {
49- if ( options . l ) totalOutput += `${ totalLines } ` ;
50- if ( options . w ) totalOutput += `${ totalWords } ` ;
51- if ( options . c ) totalOutput += `${ totalChars } ` ;
52- } else {
53- totalOutput += `${ totalLines } ${ totalWords } ${ totalChars } ` ;
54- }
52+ const totalOutput = formatCounts ( totalLines , totalWords , totalChars , options ) ;
5553
5654 console . log ( `${ totalOutput } total` ) ;
5755}
0 commit comments