no infinite loop on non global regex
This commit is contained in:
		
							
								
								
									
										6
									
								
								index.js
									
									
									
									
									
								
							
							
						
						
									
										6
									
								
								index.js
									
									
									
									
									
								
							| @@ -53,6 +53,12 @@ function copy_object (obj) { | |||||||
|  * @param {any} func function to execute |  * @param {any} func function to execute | ||||||
|  */ |  */ | ||||||
| function run_regex (regex, data, func) { | function run_regex (regex, data, func) { | ||||||
|  |   if (!regex.global) { | ||||||
|  |     const result = regex.exec (data); | ||||||
|  |     if (result) | ||||||
|  |       func (result); | ||||||
|  |     return; | ||||||
|  |   } | ||||||
|   let res = regex.exec (data); |   let res = regex.exec (data); | ||||||
|   while (res) { |   while (res) { | ||||||
|     func (res); |     func (res); | ||||||
|   | |||||||
| @@ -48,6 +48,27 @@ test ('run regex', (t) => { | |||||||
|   util.run_regex (regex, data, (res) => { |   util.run_regex (regex, data, (res) => { | ||||||
|     t.is (res[0], 'foo'); |     t.is (res[0], 'foo'); | ||||||
|     count++; |     count++; | ||||||
|   }) |   }); | ||||||
|   t.is (count, 2); |   t.is (count, 2); | ||||||
| }); | }); | ||||||
|  |  | ||||||
|  | test ('run non-global regex', (t) => { | ||||||
|  |   const data = 'foobarfoo'; | ||||||
|  |   const regex = /foo/u; | ||||||
|  |   let count = 0; | ||||||
|  |   util.run_regex (regex, data, (res) => { | ||||||
|  |     t.is (res[0], 'foo'); | ||||||
|  |     count++; | ||||||
|  |   }); | ||||||
|  |   t.is (count, 1); | ||||||
|  | }); | ||||||
|  |  | ||||||
|  | test ('run non-global regex without result', (t) => { | ||||||
|  |   const data = 'foobarfoo'; | ||||||
|  |   const regex = /baz/u; | ||||||
|  |   let count = 0; | ||||||
|  |   util.run_regex (regex, data, (res) => { | ||||||
|  |     count++; | ||||||
|  |   }); | ||||||
|  |   t.is (count, 0); | ||||||
|  | }); | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user