zhengyiming
2025-02-10 958b79ed89b9e742540f714a80261d222c0fc09b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// @ts-nocheck
/* eslint-disable */
 
function helperCreateTreeFunc(handle) {
  return function (obj, iterate, options, context) {
    const opts = options || {};
    const optChildren = opts.children || 'children';
    return handle(null, obj, iterate, context, [], [], optChildren, opts);
  };
}
 
function searchTreeItem(
  parentAllow,
  parent,
  obj,
  iterate,
  context,
  path,
  node,
  parseChildren,
  opts
) {
  let paths, nodes, rest, isAllow, hasChild;
  const rests = [];
  const hasOriginal = opts.original;
  const sourceData = opts.data;
  const mapChildren = opts.mapChildren || parseChildren;
  if (obj) {
    obj.forEach(function (item, index) {
      paths = path.concat(['' + index]);
      nodes = node.concat([item]);
      isAllow = parentAllow || iterate.call(context, item, index, obj, paths, parent, nodes);
      hasChild = parseChildren && item[parseChildren];
      if (isAllow || hasChild) {
        if (hasOriginal) {
          rest = item;
        } else {
          rest = Object.assign({}, item);
          if (sourceData) {
            rest[sourceData] = item;
          }
        }
        rest[mapChildren] = searchTreeItem(
          isAllow,
          item,
          item[parseChildren],
          iterate,
          context,
          paths,
          nodes,
          parseChildren,
          opts
        );
        if (isAllow || rest[mapChildren].length) {
          rests.push(rest);
        }
      } else if (isAllow) {
        rests.push(rest);
      }
    });
  }
  return rests;
}
 
/**
 * 从树结构中根据回调查找数据
 *
 * @param {Object} obj 对象/数组
 * @param {Function} iterate(item, index, items, path, parent, nodes) 回调
 * @param {Object} options {children: 'children'}
 * @param {Object} context 上下文
 * @return {Array}
 */
export const searchTree = helperCreateTreeFunc(function (
  parent,
  obj,
  iterate,
  context,
  path,
  nodes,
  parseChildren,
  opts
) {
  return searchTreeItem(0, parent, obj, iterate, context, path, nodes, parseChildren, opts);
});