@@ -2,13 +2,15 @@ var assert = require('assert');
22var dict = require ( './dict' ) ;
33var Parser = require ( './parser' ) ;
44var Handlers = require ( './handlers' ) ;
5+ var _memoize = require ( 'underscore' ) . memoize ;
56
67var JSONPath = function ( ) {
78 this . initialize . apply ( this , arguments ) ;
89} ;
910
1011JSONPath . prototype . initialize = function ( ) {
1112 this . parser = new Parser ( ) ;
13+ this . parser . parse = _memoize ( this . parser . parse )
1214 this . handlers = new Handlers ( ) ;
1315} ;
1416
@@ -119,7 +121,8 @@ JSONPath.prototype.nodes = async function(obj, string, count) {
119121
120122 if ( count === 0 ) return [ ] ;
121123
122- var path = this . parser . parse ( string ) ;
124+ // slice to copy before manipulating:
125+ var path = this . parser . parse ( string ) . slice ( ) ;
123126 var handlers = this . handlers ;
124127
125128 var partials = [ { path : [ '$' ] , value : obj } ] ;
@@ -157,7 +160,7 @@ JSONPath.prototype.nodes = async function(obj, string, count) {
157160 return count ? matches . slice ( 0 , count ) : matches ;
158161} ;
159162
160- JSONPath . prototype . stringify = async function ( path ) {
163+ JSONPath . prototype . _stringify = _memoize ( function ( path ) {
161164 assert . ok ( path , "we need a path" ) ;
162165
163166 var string = '$' ;
@@ -192,9 +195,13 @@ JSONPath.prototype.stringify = async function(path) {
192195 }
193196
194197 return string ;
198+ } , JSON . stringify )
199+
200+ JSONPath . prototype . stringify = function ( path ) {
201+ return this . _stringify ( path )
195202}
196203
197- JSONPath . prototype . _normalize = function ( path ) {
204+ JSONPath . prototype . _normalize = _memoize ( function ( path ) {
198205 assert . ok ( path , "we need a path" ) ;
199206
200207 if ( typeof path == "string" ) {
@@ -245,7 +252,7 @@ JSONPath.prototype._normalize = function(path) {
245252 }
246253
247254 throw new Error ( "couldn't understand path " + path ) ;
248- }
255+ } , JSON . stringify )
249256
250257function _is_string ( obj ) {
251258 return Object . prototype . toString . call ( obj ) == '[object String]' ;
0 commit comments