@@ -42,47 +42,54 @@ const showLines = flags.l || (!flags.l && !flags.w && !flags.c);
4242const showWords = flags . w || ( ! flags . l && ! flags . w && ! flags . c ) ;
4343const showBytes = flags . c || ( ! flags . l && ! flags . w && ! flags . c ) ;
4444
45+ function pad ( num , width = 8 ) {
46+ return num . toString ( ) . padStart ( width , ' ' ) ;
47+ }
48+
49+ function formatOutput ( { lines, words, bytes } , label ) {
50+ let output = '' ;
51+ if ( showLines ) output += pad ( lines ) ;
52+ if ( showWords ) output += pad ( words ) ;
53+ if ( showBytes ) output += pad ( bytes ) ;
54+ output += ` ${ label } ` ;
55+ return output ;
56+ }
57+
4558async function countFile ( file ) {
4659 try {
4760 const content = await fs . readFile ( file , 'utf-8' ) ;
48- const lines = content . split ( '\n' ) . filter ( line => line . trim ( ) !== '' ) . length ;
61+ const lines = content . split ( '\n' ) . length - 1 ;
4962 const words = content . trim ( ) . split ( / \s + / ) . filter ( Boolean ) . length ;
5063 const bytes = Buffer . byteLength ( content , 'utf-8' ) ;
5164
52- let output = '' ;
53- if ( showLines ) output += `${ lines } ` ;
54- if ( showWords ) output += `${ words } ` ;
55- if ( showBytes ) output += `${ bytes } ` ;
56-
57- output += file ;
65+ const counts = { lines, words, bytes } ;
66+ console . log ( formatOutput ( counts , file ) ) ;
5867
59- console . log ( output . trim ( ) ) ;
60-
61- return { lines, words, bytes } ;
68+ return counts ;
6269 } catch ( err ) {
6370 console . error ( `Cannot access '${ file } ': ${ err . message } ` ) ;
6471 return null ;
6572 }
6673}
6774
6875async function main ( ) {
69- const counts = await Promise . all ( files . map ( countFile ) ) ;
76+ // Instead of .map, I can explicitly collect promises using forEach():
77+ const promises = [ ] ;
78+ files . forEach ( file => {
79+ promises . push ( countFile ( file ) ) ;
80+ } ) ;
81+ const counts = await Promise . all ( promises ) ;
7082
7183 const validCounts = counts . filter ( c => c !== null ) ;
7284
7385 if ( validCounts . length > 1 ) {
74- const totalLines = validCounts . reduce ( ( sum , c ) => sum + c . lines , 0 ) ;
75- const totalWords = validCounts . reduce ( ( sum , c ) => sum + c . words , 0 ) ;
76- const totalBytes = validCounts . reduce ( ( sum , c ) => sum + c . bytes , 0 ) ;
77-
78- let totalOutput = '' ;
79- if ( showLines ) totalOutput += `${ totalLines } ` ;
80- if ( showWords ) totalOutput += `${ totalWords } ` ;
81- if ( showBytes ) totalOutput += `${ totalBytes } ` ;
82-
83- totalOutput += 'total' ;
86+ const totals = {
87+ lines : validCounts . reduce ( ( sum , c ) => sum + c . lines , 0 ) ,
88+ words : validCounts . reduce ( ( sum , c ) => sum + c . words , 0 ) ,
89+ bytes : validCounts . reduce ( ( sum , c ) => sum + c . bytes , 0 ) ,
90+ }
8491
85- console . log ( totalOutput . trim ( ) ) ;
92+ console . log ( formatOutput ( totals , 'total' ) ) ;
8693 }
8794}
8895
0 commit comments