Letting RegExp method return something iterable?

Tab Atkins Jr. jackalmage at gmail.com
Wed Aug 28 07:58:07 PDT 2013


On Wed, Aug 28, 2013 at 2:12 AM, Forbes Lindesay <forbes at lindesay.co.uk> wrote:
> Right, my impression is that most of us are in agreement that it would be extremely useful to have a simple way to loop over the list of matches for a regular expression and do something with each one.  I don't see why @andrea doesn't see this need (maybe it's not something he's found need to do recently).
>
> I think to move on, it would be useful to consider whether the method should return an array (which would be iterable and also have methods like `.map` built in) or a custom, lazy iterable (which might be better for efficiency if that laziness were useful, but will have disadvantages like lacking the array prototype methods and _presumably_ failing if you try to loop over it twice).
>
> I'm guessing that code like:
>
> ```js
> var matches = /foo/.execMultipleLazy('str')
> for (let match of matches) {
>   //do something
> }
> for (let match of matches) {
>   //do something
> }
> for (let match of matches) {
>   //do something
> }
> ```
>
> Would go wrong somehow whereas:
>
> ```js
> var matches = /foo/.execMultipleGreedy('str')
> for (let match of matches) {
>   //do something
> }
> for (let match of matches) {
>   //do something
> }
> for (let match of matches) {
>   //do something
> }
> ```

Yes.  This is a standard Python issue - if you want to make sure you
can loop over something twice, regardless of whether it's an array or
an iterator, just pass it through list() first.

Similarly, in JS you'd just pass it through Array.from() first.

~TJ


More information about the es-discuss mailing list