@@ -4,55 +4,48 @@ const escapeRegExp = require('./escape_regexp');
44
55const rParam = / : ( \w * [ ^ _ \W ] ) / g;
66
7- function Permalink ( rule , options ) {
8- if ( ! rule ) throw new TypeError ( 'rule is required!' ) ;
9- options = options || { } ;
10-
11- const segments = options . segments || { } ;
12- const params = [ ] ;
13-
14- const regex = escapeRegExp ( rule )
15- . replace ( rParam , ( match , name ) => {
16- params . push ( name ) ;
17-
18- if ( Object . prototype . hasOwnProperty . call ( segments , name ) ) {
19- const segment = segments [ name ] ;
20-
21- if ( segment instanceof RegExp ) {
22- return segment . source ;
7+ class Permalink {
8+ constructor ( rule , options ) {
9+ if ( ! rule ) { throw new TypeError ( 'rule is required!' ) ; }
10+ options = options || { } ;
11+ const segments = options . segments || { } ;
12+ const params = [ ] ;
13+ const regex = escapeRegExp ( rule )
14+ . replace ( rParam , ( match , name ) => {
15+ params . push ( name ) ;
16+ if ( Object . prototype . hasOwnProperty . call ( segments , name ) ) {
17+ const segment = segments [ name ] ;
18+ if ( segment instanceof RegExp ) {
19+ return segment . source ;
20+ }
21+ return segment ;
2322 }
23+ return '(.+?)' ;
24+ } ) ;
25+ this . rule = rule ;
26+ this . regex = new RegExp ( `^${ regex } $` ) ;
27+ this . params = params ;
28+ }
2429
25- return segment ;
26- }
27-
28- return '(.+?)' ;
29- } ) ;
30-
31- this . rule = rule ;
32- this . regex = new RegExp ( `^${ regex } $` ) ;
33- this . params = params ;
34- }
35-
36- Permalink . prototype . test = function ( str ) {
37- return this . regex . test ( str ) ;
38- } ;
39-
40- Permalink . prototype . parse = function ( str ) {
41- const match = str . match ( this . regex ) ;
42- const { params } = this ;
43- const result = { } ;
44-
45- if ( ! match ) return ;
30+ test ( str ) {
31+ return this . regex . test ( str ) ;
32+ }
4633
47- for ( let i = 1 , len = match . length ; i < len ; i ++ ) {
48- result [ params [ i - 1 ] ] = match [ i ] ;
34+ parse ( str ) {
35+ const match = str . match ( this . regex ) ;
36+ const { params } = this ;
37+ const result = { } ;
38+ if ( ! match ) { return ; }
39+ for ( let i = 1 , len = match . length ; i < len ; i ++ ) {
40+ result [ params [ i - 1 ] ] = match [ i ] ;
41+ }
42+ return result ;
4943 }
5044
51- return result ;
52- } ;
45+ stringify ( data ) {
46+ return this . rule . replace ( rParam , ( match , name ) => data [ name ] ) ;
47+ }
48+ }
5349
54- Permalink . prototype . stringify = function ( data ) {
55- return this . rule . replace ( rParam , ( match , name ) => data [ name ] ) ;
56- } ;
5750
5851module . exports = Permalink ;
0 commit comments