1+ const fs = require ( "fs" ) ;
2+ const path = require ( "path" ) ;
3+
4+ const args = process . argv . slice ( 2 ) ;
5+
6+ let countLines = false ;
7+ let countWords = false ;
8+ let countBytes = false ;
9+
10+ let files = [ ] ;
11+
12+ for ( const arg of args ) {
13+ if ( arg === "-l" ) {
14+ countLines = true ;
15+ } else if ( arg === "-w" ) {
16+ countWords = true ;
17+ } else if ( arg === "-c" ) {
18+ countBytes = true ;
19+ } else {
20+ files . push ( arg ) ;
21+ }
22+ }
23+
24+ function expandWildcard ( filePath ) {
25+ if ( ! filePath . includes ( "*" ) ) {
26+ return [ filePath ] ;
27+ }
28+
29+ const dir = path . dirname ( filePath ) ;
30+ const files = fs . readdirSync ( dir ) ;
31+
32+ return files . map ( file => path . join ( dir , file ) ) ;
33+ }
34+
35+ function getStats ( filename ) {
36+
37+ const content = fs . readFileSync ( filename , "utf8" ) ;
38+
39+ const lines = content . split ( "\n" ) . length - 1 ;
40+
41+ const words = content
42+ . trim ( )
43+ . split ( / \s + / )
44+ . filter ( word => word . length > 0 )
45+ . length ;
46+
47+ const bytes = fs . statSync ( filename ) . size ;
48+
49+ return {
50+ lines,
51+ words,
52+ bytes
53+ } ;
54+ }
55+
56+ function printResult ( stats , filename , showFilename = true ) {
57+
58+ let output = [ ] ;
59+
60+ if ( ! countLines && ! countWords && ! countBytes ) {
61+ output . push ( stats . lines ) ;
62+ output . push ( stats . words ) ;
63+ output . push ( stats . bytes ) ;
64+ } else {
65+ if ( countLines ) {
66+ output . push ( stats . lines ) ;
67+ }
68+
69+ if ( countWords ) {
70+ output . push ( stats . words ) ;
71+ }
72+
73+ if ( countBytes ) {
74+ output . push ( stats . bytes ) ;
75+ }
76+ }
77+
78+ if ( showFilename ) {
79+ output . push ( filename ) ;
80+ }
81+
82+ console . log ( output . join ( " " ) ) ;
83+ }
84+
85+ let allFiles = [ ] ;
86+
87+ for ( const file of files ) {
88+ allFiles . push ( ...expandWildcard ( file ) ) ;
89+ }
90+
91+ let total = {
92+ lines : 0 ,
93+ words : 0 ,
94+ bytes : 0
95+ } ;
96+
97+ for ( const file of allFiles ) {
98+
99+ const stats = getStats ( file ) ;
100+
101+ total . lines += stats . lines ;
102+ total . words += stats . words ;
103+ total . bytes += stats . bytes ;
104+
105+ printResult ( stats , file ) ;
106+ }
107+ if ( allFiles . length > 1 ) {
108+ printResult ( total , "total" ) ;
109+ }
0 commit comments