[algorithm] Non-recursive depth first search algorithm

An ES6 implementation based on biziclops great answer:

_x000D_
_x000D_
root = {_x000D_
  text: "root",_x000D_
  children: [{_x000D_
    text: "c1",_x000D_
    children: [{_x000D_
      text: "c11"_x000D_
    }, {_x000D_
      text: "c12"_x000D_
    }]_x000D_
  }, {_x000D_
    text: "c2",_x000D_
    children: [{_x000D_
      text: "c21"_x000D_
    }, {_x000D_
      text: "c22"_x000D_
    }]_x000D_
  }, ]_x000D_
}_x000D_
_x000D_
console.log("DFS:")_x000D_
DFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
console.log("BFS:")_x000D_
BFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
function BFS(root, getChildren, visit) {_x000D_
  let nodesToVisit = [root];_x000D_
  while (nodesToVisit.length > 0) {_x000D_
    const currentNode = nodesToVisit.shift();_x000D_
    nodesToVisit = [_x000D_
      ...nodesToVisit,_x000D_
      ...(getChildren(currentNode) || []),_x000D_
    ];_x000D_
    visit(currentNode);_x000D_
  }_x000D_
}_x000D_
_x000D_
function DFS(root, getChildren, visit) {_x000D_
  let nodesToVisit = [root];_x000D_
  while (nodesToVisit.length > 0) {_x000D_
    const currentNode = nodesToVisit.shift();_x000D_
    nodesToVisit = [_x000D_
      ...(getChildren(currentNode) || []),_x000D_
      ...nodesToVisit,_x000D_
    ];_x000D_
    visit(currentNode);_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_