@@ -619,40 +619,52 @@ function negate(delimiter: string, backtrack: string) {
619
619
}
620
620
621
621
/**
622
- * Stringify token data into a path string.
622
+ * Stringify an array of tokens into a path string.
623
623
*/
624
- export function stringify ( data : TokenData ) {
625
- return data . tokens
626
- . map ( function stringifyToken ( token , index , tokens ) : string {
627
- if ( token . type === "text" ) return escapeText ( token . value ) ;
628
- if ( token . type === "group" ) {
629
- return `{${ token . tokens . map ( stringifyToken ) . join ( "" ) } }` ;
630
- }
624
+ function stringifyTokens ( tokens : Token [ ] ) : string {
625
+ let value = "" ;
626
+ let i = 0 ;
627
+
628
+ while ( i < tokens . length ) {
629
+ const token = tokens [ i ++ ] ;
631
630
632
- const isSafe =
633
- isNameSafe ( token . name ) && isNextNameSafe ( tokens [ index + 1 ] ) ;
634
- const key = isSafe ? token . name : JSON . stringify ( token . name ) ;
631
+ if ( token . type === "text" ) {
632
+ value += escapeText ( token . value ) ;
633
+ continue ;
634
+ }
635
635
636
- if ( token . type === "param" ) return `:${ key } ` ;
637
- if ( token . type === "wildcard" ) return `*${ key } ` ;
638
- throw new TypeError ( `Unexpected token: ${ token } ` ) ;
639
- } )
640
- . join ( "" ) ;
636
+ if ( token . type === "group" ) {
637
+ value += `{${ stringifyTokens ( token . tokens ) } }` ;
638
+ continue ;
639
+ }
640
+
641
+ const isSafe = isNameSafe ( token . name ) && isNextNameSafe ( tokens [ i ] ) ;
642
+ const name = isSafe ? token . name : JSON . stringify ( token . name ) ;
643
+ value += token . type === "param" ? `:${ name } ` : `*${ name } ` ;
644
+ }
645
+
646
+ return value ;
647
+ }
648
+
649
+ /**
650
+ * Stringify token data into a path string.
651
+ */
652
+ export function stringify ( data : TokenData ) {
653
+ return stringifyTokens ( data . tokens ) ;
641
654
}
642
655
643
656
/**
644
657
* Validate the parameter name contains valid ID characters.
645
658
*/
646
659
function isNameSafe ( name : string ) {
647
660
const [ first , ...rest ] = name ;
648
- if ( ! ID_START . test ( first ) ) return false ;
649
- return rest . every ( ( char ) => ID_CONTINUE . test ( char ) ) ;
661
+ return ID_START . test ( first ) && rest . every ( ( char ) => ID_CONTINUE . test ( char ) ) ;
650
662
}
651
663
652
664
/**
653
665
* Validate the next token does not interfere with the current param name.
654
666
*/
655
667
function isNextNameSafe ( token : Token | undefined ) {
656
- if ( ! token || token . type !== "text" ) return true ;
657
- return ! ID_CONTINUE . test ( token . value [ 0 ] ) ;
668
+ if ( token && token . type === "text" ) return ! ID_CONTINUE . test ( token . value [ 0 ] ) ;
669
+ return true ;
658
670
}
0 commit comments