Cool. Like this?
function* iterTree(tree) {
if (Array.isArray(tree)) {
// inner node
for(let i=0; i < tree.length; i++) {
yield* iterTree(tree[i]);
}
} else {
// leaf
yield tree;
}
}
On May 9, 2012, at 1:20 , Erik Arvidsson wrote:
> You can use yield* here.
>
> On May 8, 2012 4:12 PM, "Axel Rauschmayer" <[email protected]> wrote:
> The following generator produces an iterator for nested arrays. Is this the
> best way to do recursion? Doesn’t seem terribly elegant.
>
> function* iterTree(tree) {
> if (Array.isArray(tree)) {
> // inner node
> for(let i=0; i < tree.length; i++) {
> for(let elem of iterTree(tree[i])) {
> yield elem;
> }
> }
> } else {
> // leaf
> yield tree;
> }
> }
>
> Interaction:
>
> $ let g = iterTree([[0, 1], 2]);
> $ g.next()
> 0
> $ g.next()
> 1
> $ g.next()
> 2
> $ g.next()
> [object StopIteration]
--
Dr. Axel Rauschmayer
[email protected]
home: rauschma.de
twitter: twitter.com/rauschma
blog: 2ality.com
_______________________________________________
es-discuss mailing list
[email protected]
https://mail.mozilla.org/listinfo/es-discuss