1+ const fs = require ( "fs" ) ;
2+
3+ const args = process . argv . slice ( 2 ) ;
4+
5+ const showLines = args . includes ( "-l" ) ;
6+ const showWords = args . includes ( "-w" ) ;
7+ const showBytes = args . includes ( "-c" ) ;
8+
9+ const files = args . filter ( a => ! a . startsWith ( "-" ) ) ;
10+
11+ function getStats ( text ) {
12+ return {
13+ lines : text . split ( "\n" ) . length - 1 ,
14+ words : text . trim ( ) . split ( / \s + / ) . filter ( Boolean ) . length ,
15+ bytes : Buffer . byteLength ( text )
16+ } ;
17+ }
18+
19+ function format ( num ) {
20+ return String ( num ) . padStart ( 8 ) ;
21+ }
22+
23+ let totalLines = 0 ;
24+ let totalWords = 0 ;
25+ let totalBytes = 0 ;
26+
27+ files . forEach ( file => {
28+ const content = fs . readFileSync ( file , "utf8" ) ;
29+ const stats = getStats ( content ) ;
30+
31+ totalLines += stats . lines ;
32+ totalWords += stats . words ;
33+ totalBytes += stats . bytes ;
34+
35+ let output = [ ] ;
36+
37+ if ( showLines ) output . push ( format ( stats . lines ) ) ;
38+ else if ( showWords ) output . push ( format ( stats . words ) ) ;
39+ else if ( showBytes ) output . push ( format ( stats . bytes ) ) ;
40+ else output . push ( format ( stats . lines ) , format ( stats . words ) , format ( stats . bytes ) ) ;
41+
42+ output . push ( file ) ;
43+
44+ console . log ( output . join ( " " ) ) ;
45+ } ) ;
46+
47+ if ( files . length > 1 ) {
48+ let output = [ ] ;
49+
50+ if ( showLines ) output . push ( format ( totalLines ) ) ;
51+ else if ( showWords ) output . push ( format ( totalWords ) ) ;
52+ else if ( showBytes ) output . push ( format ( totalBytes ) ) ;
53+ else output . push ( format ( totalLines ) , format ( totalWords ) , format ( totalBytes ) ) ;
54+
55+ output . push ( "total" ) ;
56+
57+ console . log ( output . join ( " " ) ) ;
58+ }
0 commit comments