DEV Community

myleftshoe
myleftshoe

Posted on

Evolutionary dead-ends (finding childless descendants aka leaf nodes)

There goes the bloodline ☹️

In the following examples get_n_children() returns the number of children the actor has and get_children() returns the children as an array.

Method 1: Standard recursion

function get_childless_descendants(actor) {
    const leafs = []
    recurse(actor)
    return leafs
    function recurse(actor) {
        if (actor.get_n_children()) {
            actor.get_children().forEach(recurse)
            return
        }
        leafs.push(actor)
    }
}
Enter fullscreen mode Exit fullscreen mode

Method 2: Functional using a recursive reducer

function get_childless_descendants_using_reduce(actor) {
    const leafs = (acc, cur) => cur.get_n_children() 
        ? cur.get_children().reduce(leafs, acc) 
        : [...acc, cur]
    return leafs([], actor)
}
Enter fullscreen mode Exit fullscreen mode

Method 3: Functional using a recursive flatMap

function get_childless_descendants_using_flatMap(actor) {
    const leafs = (actor) => actor.get_n_children() 
        ? actor.get_children().flatMap(leafs) 
        : [ actor ]
    return leafs(actor)
}
Enter fullscreen mode Exit fullscreen mode

TODO: What happens when the tree is large? Recursion is expensive - an iterator/generator version could be used to find the leaf nodes one at a time, on demand.

Do you have another method?

Discussion (0)