1+ const match = ( payload , pattern ) => {
2+ let result = { match : true , total : 0 , matches : { } , groups : { } } ;
3+ let node = result . matches ;
4+
5+ const tester = ( payload , pattern , current_node ) => {
6+
7+ Object . entries ( pattern ) . forEach ( ( [ key , value ] ) => {
8+ if ( value instanceof RegExp ) {
9+ const matcher = payload [ key ] . match ( value ) || [ ] ;
10+ if ( matcher . length > 0 ) {
11+ result . groups = { ...result . groups , ...matcher . groups } ;
12+ current_node [ key ] = payload [ key ] ;
13+ result . total += 1 ;
14+ } else {
15+ result . match = false ;
16+ }
17+ } else if ( value instanceof Array ) {
18+ current_node [ key ] = [ ] ;
19+ value . forEach ( ( element , index ) => {
20+ if ( element instanceof RegExp ) {
21+ const matcher = payload [ key ] [ index ] . match ( element ) || [ ] ;
22+ if ( matcher . length > 0 ) {
23+ result . groups = { ...result . groups , ...matcher . groups } ;
24+ current_node [ key ] = payload [ key ] ;
25+ result . total += 1 ;
26+ } else {
27+ result . match = false ;
28+ }
29+ } else if ( element instanceof Object ) {
30+ current_node [ key ] [ index ] = { } ;
31+ tester ( payload [ key ] [ index ] , element , current_node [ key ] [ index ] ) ;
32+ } else if ( payload [ key ] . includes ( element ) ) {
33+ current_node [ key ] [ index ] = element ;
34+ result . total += 1 ;
35+ } else {
36+ result . match = false ;
37+ }
38+ } ) ;
39+ } else if ( value instanceof Object ) {
40+ current_node [ key ] = { } ;
41+ tester ( payload [ key ] , value , current_node [ key ] ) ;
42+ } else {
43+ if ( payload [ key ] != value ) {
44+ result . match = false ;
45+ } else {
46+ current_node [ key ] = payload [ key ] ;
47+ result . total += 1 ;
48+ }
49+ }
50+ } )
51+ }
52+
53+ tester ( payload , pattern , node ) ;
54+
55+ return result ;
56+ }
57+
58+ module . exports = match ;
0 commit comments