Search code examples
javascriptalgorithmtreetraversalbreadth-first-search

Difference in syntax of a function that I cannot understand


I was writing a function for a Breadth first search alogrithm. I would have come up with the following code

traverseBF() {
        const results = []
        const queue = [this.root]
        while (queue.length) {
            let node = queue.shift()
            if (node.children) {
                queue.push(...node.children)
            }
            results.push(node)
        }
        return results
    }

However, the solution was written somewhat differently as

traverseBF(fn) {
        const queue = [this.root]
        while (queue.length) {
            let node = queue.shift()
            if (node.children) {
                queue.push(...node.children)
            }
            fn(node)
        }
    }

I cannot explain what fn(node) purpose is or how it returns the correct result. Is this some kind of recursive call? How are the two solutions different?


Solution

  • Instead of returning results like you are, they're allowing the user to pass in a function that gets passed each node as it's traversed.

    Try for example:

    obj.traverseBF(node => console.log(node))
    

    Or just

    obj.traverseBF(console.log)
    

    Should work as well. console.log is given each node to use as it's found.

    This is arguably more general purpose. If the tree was large, accumulating all the results in a list may waste memory if the user doesn't need all the results at once.

    If the user wanted to accumulate a list though, they could pass in a function that appends to a list that the function closes over:

    nodes = [];
    obj.traverseBF(node => nodes.push(node))
    
    console.log(nodes)