@@ -588,32 +588,34 @@ JSONPath.prototype._slice = function (
588
588
JSONPath . prototype . _eval = function (
589
589
code , _v , _vname , path , parent , parentPropName
590
590
) {
591
- if ( code . includes ( '@parentProperty' ) ) {
592
- this . currSandbox . _$_parentProperty = parentPropName ;
593
- code = code . replace ( / @ p a r e n t P r o p e r t y / gu, '_$_parentProperty' ) ;
594
- }
595
- if ( code . includes ( '@parent' ) ) {
596
- this . currSandbox . _$_parent = parent ;
597
- code = code . replace ( / @ p a r e n t / gu, '_$_parent' ) ;
598
- }
599
- if ( code . includes ( '@property' ) ) {
600
- this . currSandbox . _$_property = _vname ;
601
- code = code . replace ( / @ p r o p e r t y / gu, '_$_property' ) ;
602
- }
603
- if ( code . includes ( '@path' ) ) {
591
+ this . currSandbox . _$_parentProperty = parentPropName ;
592
+ this . currSandbox . _$_parent = parent ;
593
+ this . currSandbox . _$_property = _vname ;
594
+ this . currSandbox . _$_root = this . json ;
595
+ this . currSandbox . _$_v = _v ;
596
+
597
+ const containsPath = code . includes ( '@path' ) ;
598
+ if ( containsPath ) {
604
599
this . currSandbox . _$_path = JSONPath . toPathString ( path . concat ( [ _vname ] ) ) ;
605
- code = code . replace ( / @ p a t h / gu, '_$_path' ) ;
606
- }
607
- if ( code . includes ( '@root' ) ) {
608
- this . currSandbox . _$_root = this . json ;
609
- code = code . replace ( / @ r o o t / gu, '_$_root' ) ;
610
600
}
611
- if ( ( / @ ( [ . \s ) [ ] ) / u) . test ( code ) ) {
612
- this . currSandbox . _$_v = _v ;
613
- code = code . replace ( / @ ( [ . \s ) [ ] ) / gu, '_$_v$1' ) ;
601
+
602
+ const scriptCacheKey = 'script:' + code ;
603
+ if ( ! JSONPath . cache [ scriptCacheKey ] ) {
604
+ let script = code
605
+ . replace ( / @ p a r e n t P r o p e r t y / gu, '_$_parentProperty' )
606
+ . replace ( / @ p a r e n t / gu, '_$_parent' )
607
+ . replace ( / @ p r o p e r t y / gu, '_$_property' )
608
+ . replace ( / @ r o o t / gu, '_$_root' )
609
+ . replace ( / @ ( [ . \s ) [ ] ) / gu, '_$_v$1' ) ;
610
+ if ( containsPath ) {
611
+ script = script . replace ( / @ p a t h / gu, '_$_path' ) ;
612
+ }
613
+
614
+ JSONPath . cache [ scriptCacheKey ] = new this . vm . Script ( script ) ;
614
615
}
616
+
615
617
try {
616
- return this . vm . runInNewContext ( code , this . currSandbox ) ;
618
+ return JSONPath . cache [ scriptCacheKey ] . runInNewContext ( this . currSandbox ) ;
617
619
} catch ( e ) {
618
620
throw new Error ( 'jsonPath: ' + e . message + ': ' + code ) ;
619
621
}
0 commit comments