@@ -25,41 +25,45 @@ const opts = program.opts();
2525
2626const total = [ ] ;
2727const output = [ ] ;
28+ const countsPerFile = [ ] ;
29+ let columnWidth = 0 ;
2830
2931const flag_c = ( content ) => {
30- output . push ( Buffer . byteLength ( content , "utf8" ) ) ;
32+ return Buffer . byteLength ( content , "utf8" ) ;
3133} ;
3234
3335const flag_w = ( content ) => {
34- output . push ( content . match ( / \b [ \w ' ] + \b / g) . length ) ;
36+ return content . match ( / \b [ \w ' ] + \b / g) . length ;
3537} ;
3638
3739const flag_l = ( content ) => {
38- output . push ( content . split ( "\n" ) . length - 1 ) ;
40+ return content . split ( "\n" ) . length - 1 ;
3941} ;
4042
4143const countAndDisplay = async ( path ) => {
44+ const outputPerFile = [ ] ;
4245 const content = await fs . readFile ( path , "utf-8" ) ;
43- output . splice ( 0 ) ;
4446 if ( opts [ "l" ] ) {
45- flag_l ( content ) ;
47+ outputPerFile . push ( flag_l ( content ) ) ;
4648 }
4749 if ( opts [ "w" ] ) {
48- flag_w ( content ) ;
50+ outputPerFile . push ( flag_w ( content ) ) ;
4951 }
5052 if ( opts [ "c" ] ) {
51- flag_c ( content ) ;
53+ outputPerFile . push ( flag_c ( content ) ) ;
5254 }
5355 if ( argv . length > 1 ) {
5456 if ( total . length == 0 ) {
55- total . push ( ...output ) ;
57+ total . push ( ...outputPerFile ) ;
5658 } else {
57- for ( let index = 0 ; index < output . length ; index ++ ) {
58- total [ index ] += output [ index ] ;
59+ for ( let index = 0 ; index < outputPerFile . length ; index ++ ) {
60+ total [ index ] += outputPerFile [ index ] ;
5961 }
6062 }
63+ countsPerFile . push ( ...outputPerFile ) ;
6164 }
62- console . log ( [ ...output , path ] . join ( " " ) ) ;
65+ outputPerFile . push ( path ) ;
66+ output . push ( [ ...outputPerFile ] ) ;
6367} ;
6468
6569const handleInput = async ( ) => {
@@ -69,8 +73,23 @@ const handleInput = async () => {
6973 for ( const path of argv ) {
7074 await countAndDisplay ( path ) ;
7175 }
76+ const numOfColumns = Object . keys ( opts ) . length ;
7277 if ( argv . length > 1 ) {
73- console . log ( `${ total . join ( " " ) } total` ) ;
78+ total . push ( "total" ) ;
79+ output . push ( total ) ;
80+ }
81+ for ( const row of output ) {
82+ for ( let i = 0 ; i < numOfColumns ; i ++ ) {
83+ columnWidth = Math . max ( columnWidth , String ( row [ i ] ) . length ) ;
84+ }
85+ }
86+
87+ for ( let row of output ) {
88+ const line_parts = [ ] ;
89+ for ( let i = 0 ; i < numOfColumns ; i ++ ) {
90+ line_parts . push ( String ( row [ i ] ) . padStart ( columnWidth + 4 ) ) ;
91+ }
92+ console . log ( line_parts . join ( " " ) , row . at ( - 1 ) ) ;
7493 }
7594} ;
7695handleInput ( ) ;
0 commit comments