Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript function using recursion and yield keyword to pull out nested lists

I'm trying to rewrite a C# function that uses yield and recursion to pull out instances of a class out of nested lists into a single list.

This is the C# function:

 public static IEnumerable<TargetObject> GetRecursively(params TargetObject[] startingObjects)
 {
    foreach (TargetObject startingObject in startingObjects)
    {
        yield return startingObject;
        if (startingObject.InnerObjects != null)
            foreach (TargetObject innerObject in startingObject.InnerObjects.ToArray())
                foreach (TargetObject recursiveInner in GetRecursively(innerObject))
                    yield return recursiveInner;
     }
 }

Being that javascript doesn't reliably support yield across browsers, how can I simulate it in this complex function?

function getRecursively(...startingObjects: TargetObject[])
{
    return function () {
           ??
    }
}
like image 977
parliament Avatar asked Sep 16 '25 22:09

parliament


1 Answers

Update for 2019

This is now super easy with typescript (or es6)

function* recursiveIterator( obj: { children?: any[]; } ):IterableIterator<any> {
    yield obj;
    for ( const child of obj.children ) {
        yield* recursiveIterator( child );
    }
}
like image 63
JasonS Avatar answered Sep 19 '25 14:09

JasonS