helper.js 755 B

12345678910111213141516171819202122
  1. /**
  2. * 深度优先遍历算法, 遍历tree的每一项
  3. * @param {Object} {tree, path: 父节点的path, init: 是否是初始化}
  4. * @param {Callback}} cb 回调函数,参数为 node
  5. */
  6. export function depthFirstEach({ tree, parent = null }, cb) {
  7. if (!Array.isArray(tree)) {
  8. console.warn('The tree in the first argument to function depthFirstEach must be an array');
  9. return;
  10. }
  11. if (!tree || tree.length === 0) return;
  12. for (let node of tree) {
  13. const hasChildren = node.children && node.children.length > 0;
  14. if (cb) {
  15. const res = cb(node);
  16. if (res === 'break') return;
  17. }
  18. if (hasChildren) {
  19. depthFirstEach({ tree: node.children }, cb);
  20. }
  21. }
  22. }