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 () {
??
}
}
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 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With