Rewrite Descendants(ContainerInline) iteratively

This commit is contained in:
Miha Zupan
2019-01-18 18:52:48 +01:00
parent 4519d3820a
commit 282da043b7

View File

@@ -94,25 +94,36 @@ namespace Markdig.Syntax.Inlines
/// <returns>An enumeration of T</returns>
public IEnumerable<T> FindDescendants<T>() where T : Inline
{
var child = FirstChild;
while (child != null)
{
var next = child.NextSibling;
// Fast-path an empty container to avoid allocating a Stack
if (LastChild == null) yield break;
if (child is T)
{
yield return (T)child;
}
Stack<Inline> stack = new Stack<Inline>();
if (child is ContainerInline)
{
foreach (var subChild in ((ContainerInline) child).FindDescendants<T>())
{
yield return subChild;
}
}
child = next;
var child = LastChild;
while (child != null)
{
stack.Push(child);
child = child.PreviousSibling;
}
while (stack.Count > 0)
{
child = stack.Pop();
if (child is T childT)
{
yield return childT;
}
if (child is ContainerInline containerInline)
{
child = containerInline.LastChild;
while (child != null)
{
stack.Push(child);
child = child.PreviousSibling;
}
}
}
}