All files / utils TreeData.ts

100% Statements 150/150
93.65% Branches 59/63
100% Functions 44/44
100% Lines 140/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637                                                                                                                                                                                                            36x   36x     36x                       36x 36x       56x                                         44x 44x 434x       44x 44x 44x 44x 291x 44x 62x 44x 3730x   3730x 3730x 3730x   3730x                     3730x 291x       42x   291x     3730x   3727x           3355x 3015x 3045x                   340x 300x                           41x   41x 290x                     36x 36x 36x 36x                                   39x           39x 39x 39x   44x 39x 44x                 39x                           1x                           1x                         36x             36x                 1x                 1x                 1x 10x 10x     1x                                               4x 338x 558x     4x                     2x 220x 220x     2x                     1x 10x 20x 10x       1x                     4x   340x 31x 31x   31x 30x   31x       331x 31x   331x 270x   331x 331x     4x                       2x 124x 1x 1x     2x                     5x 5x 550x 13x     5x                       2x 124x 1x 1x     2x                     2x 2x 220x 1x     2x                       1x 13x 1x 1x 1x     1x                     1x 1x 110x 10x 10x     1x                     2x 2x 220x 120x     2x             1x             19x             1x 1x 110x   1x                             1x 1x 8x 8x 8x   1x 1x 8x 8x 4x   4x     1x      
import { cloneDeepFast } from './cloneDeepFast'
import { Merge, OneOrMore } from '../types'
 
export interface TreeDataNode extends Record<any, any> {}
 
export type TreeDataSingleRootData<TNode extends TreeDataNode> = TNode
 
export type TreeDataMultipleRootData<TNode extends TreeDataNode> = TNode[]
 
export type TreeDataStandardNode<TNode extends TreeDataNode> = Merge<
  TNode,
  {
    children: Array<TreeDataStandardNode<TNode>>
  }
>
 
export type TreeDataData<TNode extends TreeDataNode> = TNode[]
 
export type TreeDataChildrenPropName<TNode extends TreeDataNode> = {
  [K in keyof TNode]: Exclude<TNode[K], undefined> extends TreeDataData<TNode>
    ? K
    : never
}[keyof TNode]
 
export type TreeDataSearchStrategy = 'DFS' | 'BFS'
 
export interface TreeDataOptions<TNode extends TreeDataNode> {
  /**
   * 节点上子树数据所在的属性名。
   *
   * @default 'children'
   */
  childrenPropName?: TreeDataChildrenPropName<TNode>
 
  /**
   * 遍历时的搜索策略。
   *
   * - `DFS`: 深度优先搜索
   * - `BFS`: 广度优先搜索
   *
   * @default 'DFS'
   */
  searchStrategy?: TreeDataSearchStrategy
 
  /**
   * 克隆数据时忽略的值。
   */
  cloneIgnore?: (value: unknown) => boolean | undefined
}
 
export interface TreeDataTraverseFnPayload<TNode extends TreeDataNode> {
  /**
   * 当前节点。
   */
  node: TNode
 
  /**
   * 当前节点索引。
   */
  index: number
 
  /**
   * 当前深度。从 `0` 开始。
   */
  depth: number
 
  /**
   * 父节点。为 `undefined` 时表示当前节点是根节点。
   */
  parentNode: TNode | undefined
 
  /**
   * 到当前节点的路径节点列表。
   */
  path: TNode[]
 
  /**
   * 移除当前节点。
   */
  removeNode: () => void
 
  /**
   * 退出遍历。
   */
  exit: () => void
 
  /**
   * 跳过子树遍历。
   */
  skipChildrenTraverse: () => void
}
 
export type TreeDataTraverseFn<TNode extends TreeDataNode> = (
  payload: TreeDataTraverseFnPayload<TNode>,
) => void
 
/**
 * 树数据处理。支持单根节点、多根节点树数据。
 */
export class TreeData<TNode extends TreeDataNode> {
  private data: TreeDataData<TNode>
 
  private childrenPropName: TreeDataChildrenPropName<TNode> = 'children' as any
 
  private searchStrategy: TreeDataSearchStrategy = 'DFS'
 
  private cloneIgnore: ((value: unknown) => boolean | undefined) | undefined =
    undefined
 
  /**
   * 构造函数。
   *
   * @param data 整棵树的数据
   * @param options 选项
   */
  constructor(
    data: TreeDataSingleRootData<TNode> | TreeDataMultipleRootData<TNode>,
    options: TreeDataOptions<TNode> = {},
  ) {
    this.setOptions(options)
    this.data = this.cloneDeep(Array.isArray(data) ? data : [data])
  }
 
  private cloneDeep<T>(value: T): T {
    return cloneDeepFast(value, this.cloneIgnore)
  }
 
  /**
   * 核心遍历函数。
   */
  private static traverse<TNode extends TreeDataNode>(
    data: TreeDataData<TNode>,
    childrenPropName: TreeDataChildrenPropName<TNode>,
    searchStrategy: TreeDataSearchStrategy,
    fn: TreeDataTraverseFn<TNode>,
  ) {
    const nodes: Array<
      [
        node: TNode,
        index: number,
        parentNode: TNode | undefined,
        siblings: TNode[],
        depth: number,
        path: TNode[],
      ]
    > = []
    for (let i = data.length - 1; i >= 0; i--) {
      nodes.push([data[i], i, undefined, data, 0, []])
    }
 
    let currentNode: typeof nodes[0] | undefined
    const removeNodes: Array<[siblings: TNode[], indexes: number[]]> = []
    let isRemove = false
    let isExit = false
    let isSkipChildrenTraverse = false
    const removeNode = () => (isRemove = true)
    const exit = () => (isExit = true)
    const skipChildrenTraverse = () => (isSkipChildrenTraverse = true)
    while ((currentNode = nodes.pop())) {
      const [node, index, parentNode, siblings, depth, path] = currentNode
 
      isRemove = false
      isExit = false
      isSkipChildrenTraverse = false
 
      fn({
        node: node,
        index: index,
        parentNode: parentNode,
        depth: depth,
        path: path,
        removeNode: removeNode,
        exit: exit,
        skipChildrenTraverse: skipChildrenTraverse,
      })
 
      if (isRemove) {
        if (
          !removeNodes.length ||
          removeNodes[removeNodes.length - 1][0] !== siblings
        ) {
          removeNodes.push([siblings, []])
        }
        removeNodes[removeNodes.length - 1][1].push(index)
      }
 
      if (isExit) return
 
      if (
        !isRemove &&
        !isSkipChildrenTraverse &&
        node[childrenPropName] &&
        Array.isArray(node[childrenPropName])
      ) {
        if (searchStrategy === 'DFS') {
          for (let i = node[childrenPropName].length - 1; i >= 0; i--) {
            nodes.push([
              node[childrenPropName][i],
              i,
              node,
              node[childrenPropName],
              depth + 1,
              path.concat(node),
            ])
          }
        } else {
          for (let i = 0; i < node[childrenPropName].length; i++) {
            nodes.unshift([
              node[childrenPropName][i],
              i,
              node,
              node[childrenPropName],
              depth + 1,
              path.concat(node),
            ])
          }
        }
      }
    }
 
    let _removeNode: typeof removeNodes[0] | undefined
    while ((_removeNode = removeNodes.pop())) {
      let removeNodeIndex: number | undefined
      while ((removeNodeIndex = _removeNode[1].pop()) != null) {
        _removeNode[0].splice(removeNodeIndex, 1)
      }
    }
  }
 
  /**
   * 设置选项。
   *
   * @param options 选项
   */
  setOptions(options: TreeDataOptions<TNode>): this {
    this.cloneIgnore = options.cloneIgnore || this.cloneIgnore
    this.childrenPropName = options.childrenPropName || this.childrenPropName
    this.searchStrategy = options.searchStrategy || this.searchStrategy
    return this
  }
 
  /**
   * 遍历节点。
   *
   * @param node 节点
   * @param fn 遍历函数
   * @param searchStrategy 遍历搜索方式,默认为选项中的遍历搜索方式
   */
  traverseNode(
    node:
      | OneOrMore<TNode>
      | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean),
    fn: OneOrMore<TreeDataTraverseFn<TNode> | false>,
    searchStrategy: TreeDataSearchStrategy = this.searchStrategy,
  ) {
    const nodes: TNode[] =
      typeof node === 'function'
        ? this.findNodeAll(node as any)
        : Array.isArray(node)
        ? node
        : [node]
    let _node: TNode | undefined
    while ((_node = nodes.pop())) {
      if (Array.isArray(_node[this.childrenPropName])) {
        const fns: Array<TreeDataTraverseFn<TNode>> = (
          Array.isArray(fn) ? fn : [fn]
        ).filter(fn => typeof fn === 'function') as any
        for (let i = 0; i < fns.length; i++) {
          TreeData.traverse<TNode>(
            _node[this.childrenPropName],
            this.childrenPropName,
            searchStrategy,
            fns[i],
          )
        }
      }
    }
    return this
  }
 
  /**
   * 深度优先遍历节点。
   *
   * @param fn 遍历函数
   */
  traverseNodeDFS(
    node:
      | OneOrMore<TNode>
      | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean),
    fn: OneOrMore<TreeDataTraverseFn<TNode> | false>,
  ): this {
    return this.traverseNode(node, fn, 'DFS')
  }
 
  /**
   * 广度优先遍历节点。
   *
   * @param fn 遍历函数
   */
  traverseNodeBFS(
    node:
      | OneOrMore<TNode>
      | ((payload: TreeDataTraverseFnPayload<TNode>) => boolean),
    fn: OneOrMore<TreeDataTraverseFn<TNode> | false>,
  ): this {
    return this.traverseNode(node, fn, 'BFS')
  }
 
  /**
   * 遍历。
   *
   * @param fn 遍历函数
   * @param searchStrategy 遍历搜索方式,默认为选项中的遍历搜索方式
   */
  traverse(
    fn: OneOrMore<TreeDataTraverseFn<TNode> | false>,
    searchStrategy: TreeDataSearchStrategy = this.searchStrategy,
  ): this {
    this.traverseNode(
      {
        [this.childrenPropName]: this.data,
      } as any,
      fn,
      searchStrategy,
    )
    return this
  }
 
  /**
   * 深度优先遍历。
   *
   * @param fn 遍历函数
   */
  traverseDFS(fn: OneOrMore<TreeDataTraverseFn<TNode> | false>): this {
    return this.traverse(fn, 'DFS')
  }
 
  /**
   * 广度优先遍历。
   *
   * @param fn 遍历函数
   */
  traverseBFS(fn: OneOrMore<TreeDataTraverseFn<TNode> | false>): this {
    return this.traverse(fn, 'BFS')
  }
 
  /**
   * 设置数据深度。从 `0` 开始,将会移除超过指定深度的数据。
   *
   * @param depth 深度
   */
  setDepth(depth: number): this {
    this.traverse(payload => {
      if (payload.depth === depth) {
        delete payload.node[this.childrenPropName]
      }
    })
    return this
  }
 
  /**
   * 设置节点属性。
   *
   * @param props 节点属性键值映射对象,值为函数,用其返回值作为新的属性值
   */
  setNodeProps<
    TProps extends {
      [K in keyof TNode]?: (payload: TreeDataTraverseFnPayload<TNode>) => any
    } & {
      [K: string]: (payload: TreeDataTraverseFnPayload<TNode>) => any
    },
  >(
    props: TProps,
  ): TreeData<
    Merge<
      TNode,
      {
        [K in keyof TProps]: ReturnType<TProps[K]>
      }
    >
  > {
    this.traverse(payload => {
      for (const propName in props) {
        ;(payload.node as any)[propName] = props[propName](payload)
      }
    })
    return this as any
  }
 
  /**
   * 移除节点上指定的属性。
   *
   * @param propNames 属性名列表
   */
  omitNodeProps<TPropName extends keyof TNode>(
    propNames: TPropName[],
  ): TreeData<Omit<TNode, TPropName>> {
    this.traverse(payload => {
      for (const i in propNames) {
        delete payload.node[propNames[i]]
      }
    })
    return this as any
  }
 
  /**
   * 选取节点上指定的属性。
   *
   * @param propNames 属性名列表
   */
  pickNodeProps<TPropName extends keyof TNode>(
    propNames: TPropName[],
  ): TreeData<Pick<TNode, TPropName>> {
    this.traverse(payload => {
      for (const propName in payload.node) {
        if (propNames.indexOf(propName as any) === -1) {
          delete payload.node[propName]
        }
      }
    })
    return this as any
  }
 
  /**
   * 筛选符合条件的节点。
   *
   * @param predicate 条件
   */
  filter(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): this {
    this.traverse([
      payload => {
        if (predicate(payload)) {
          ;(payload.node as any).__SKIP__ = true
          ;(payload.node as any).__PICK__ = true
          let node: TNode | undefined
          while ((node = payload.path.pop())) {
            ;(node as any).__PICK__ = true
          }
          payload.skipChildrenTraverse()
        }
      },
      payload => {
        if (payload.node.__SKIP__ === true) {
          payload.skipChildrenTraverse()
        }
        if (payload.node.__PICK__ !== true) {
          payload.removeNode()
        }
        delete payload.node.__SKIP__
        delete payload.node.__PICK__
      },
    ])
    return this
  }
 
  /**
   * 查找符合条件的第一个节点。
   *
   * @param predicate 条件
   */
  findNode(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): TNode | undefined {
    let node: TNode | undefined
    this.traverse(payload => {
      if (predicate(payload)) {
        node = payload.node
        payload.exit()
      }
    })
    return node
  }
 
  /**
   * 查找符合条件的所有节点。
   *
   * @param predicate 条件
   */
  findNodeAll(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): TNode[] {
    const nodes: TNode[] = []
    this.traverse(payload => {
      if (predicate(payload)) {
        nodes.push(payload.node)
      }
    })
    return nodes
  }
 
  /**
   * 查找符合条件的第一个节点的路径。
   *
   * @param predicate 条件
   */
  findNodePath(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): TNode[] | undefined {
    let path: TNode[] | undefined
    this.traverse(payload => {
      if (predicate(payload)) {
        path = payload.path.concat(payload.node)
        payload.exit()
      }
    })
    return path
  }
 
  /**
   * 查找符合条件的所有节点的路径。
   *
   * @param predicate 条件
   */
  findNodePathAll(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): Array<TNode[]> {
    const paths: Array<TNode[]> = []
    this.traverse(payload => {
      if (predicate(payload)) {
        paths.push(payload.path.concat(payload.node))
      }
    })
    return paths
  }
 
  /**
   * 移除符合条件的第一个节点。返回被移除的节点。
   *
   * @param predicate 条件
   */
  removeNode(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): TNode | undefined {
    let node: TNode | undefined
    this.traverse(payload => {
      if (predicate(payload)) {
        payload.removeNode()
        node = payload.node
        payload.exit()
      }
    })
    return node
  }
 
  /**
   * 移除符合条件的所有节点。返回被移除的节点组成的数组。
   *
   * @param predicate 条件
   */
  removeNodeAll(
    predicate: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): TNode[] {
    const nodes: TNode[] = []
    this.traverse(payload => {
      if (predicate(payload)) {
        payload.removeNode()
        nodes.push(payload.node)
      }
    })
    return nodes
  }
 
  /**
   * 计算符合条件的节点个数。不给出条件则计算所有节点的个数。
   *
   * @param predicate 条件
   */
  count(
    predicate?: (payload: TreeDataTraverseFnPayload<TNode>) => boolean,
  ): number {
    let counter = 0
    this.traverse(payload => {
      if (predicate ? predicate(payload) : true) {
        counter++
      }
    })
    return counter
  }
 
  /**
   * 克隆实例。
   */
  clone(): TreeData<TNode> {
    return new TreeData(this.export())
  }
 
  /**
   * 导出数据。
   */
  export(): TreeDataData<TNode> {
    return this.cloneDeep(this.data)
  }
 
  /**
   * 导出一维列表数据。
   */
  exportList(): TNode[] {
    const list: TNode[] = []
    this.traverse(payload => {
      list.push(payload.node)
    })
    return this.cloneDeep(list)
  }
 
  /**
   * 从一维列表生成实例。
   *
   * @param list 列表
   * @param idKey ID 所在键
   * @param parentIdKey 父 ID 所在键
   */
  static fromList<TItem extends Record<any, any>>(
    list: TItem[],
    idKey: keyof TItem,
    parentIdKey: keyof TItem,
  ): TreeData<TreeDataStandardNode<TItem>> {
    const itemMap: Record<any, TItem> = {}
    for (let i = 0; i < list.length; i++) {
      const item = list[i] as any
      item.children = []
      itemMap[item[idKey]] = item
    }
    const tree: TItem[] = []
    for (let i = 0; i < list.length; i++) {
      const item = list[i] as any
      if (itemMap[item[parentIdKey]] !== undefined) {
        itemMap[item[parentIdKey]].children.push(item)
      } else {
        tree.push(item)
      }
    }
    return new TreeData(tree as any)
  }
}