ysny.karibu-tools.karibu-tools.0.20.source-code.DepthFirstTreeIterator.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of karibu-tools Show documentation
Show all versions of karibu-tools Show documentation
Karibu-Tools: The Vaadin Missing Utilities
package com.github.mvysny.kaributools
import com.vaadin.flow.component.Component
import java.util.*
import kotlin.streams.toList
/**
* Walks the child tree, depth-first: first the node, then its descendants,
* then its next sibling.
* @param root start here.
* @param children fetches children of given node.
*/
public class DepthFirstTreeIterator(root: T, private val children: (T) -> List) : Iterator {
private val queue: Deque = LinkedList(listOf(root))
override fun hasNext(): Boolean = !queue.isEmpty()
override fun next(): T {
if (!hasNext()) throw NoSuchElementException()
val result: T = queue.pop()
children(result).asReversed().forEach { queue.push(it) }
return result
}
}
/**
* Walks the component child tree, depth-first: first the component, then its descendants,
* then its next sibling.
*/
public fun Component.walk(): Iterable = Iterable {
DepthFirstTreeIterator(this) { component: Component -> component.children.toList() }
}