JSFiddle - React, Tailwind, and code Playground

by Khalil Zhang

JavaScript

const input = [
  { id: 1, name: 'i1', parentId: 4 },
  { id: 2, name: 'i2', parentId: 1 },
  { id: 3, name: 'i3', parentId: 2 },
  { id: 4, name: 'i4', parentId: 3 },
]

class Node {
    constructor({id, name}){
        this.id = id || ''
        this.name = name || ''
        this.parent = null
        this.children = []
    }
    getId() { return this.id }
    getName() { return this.name }
    getParent() { return this.parent }
    getChildren() { return this.children }
    setId(_id) { this.id = _id}
    setName(_name) { this.name = _name}
    setParent(node) {
        if (node instanceof Node)
            this.parent = node
    }
    addChild(node) {
        if (node instanceof Node)
            this.children.push(node)
    }
    serialize() {
        return {
            id: this.getId(),
            name: this.getName(),
            parentId: this.getParent() && this.getParent().getId(),
            children: this.getChildren().length ? this.getChildren().map(node => node.serialize()) : []
        }
    }
}
class Tree {
    constructor(root) {
        this.root = root || null
        this.nodeList = new Map()
        if (this.root) {
            this.nodeList.set(this.root.getId(), this.root)
        }
    }
    getRoot() { return this.root }
    setRoot(root) {
        if (root instanceof Node)
            this.root = root
    }
    hasNode(_id) {
        return this.nodeList.has(_id)
    }
    addNode(node) {
        if (node && node instanceof Node && !this.nodeList.has(node.getId())) {
            this.nodeList.set(node.getId(), node)
        }
    }
    getNodeById(_id) {
        if (_id && this.nodeList.has(_id)) {
            return this.nodeList.get(_id)
        } else return null
    }
    getNodes() {
        return this.nodeList
    }
    getLength() {return this.nodeList.size}
    serialize() {
        return this.root.serialize()
    }
}
function transformTree(array) {
    if (!Array.isArray(array))
        throw new Error('请输入数组')
    const...