All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ysny.karibu-tools.karibu-tools.0.21.source-code.DepthFirstTreeIterator.kt Maven / Gradle / Ivy

The newest version!
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() }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy