如何在graphlib上更改节点ID?

时间:2016-12-02 01:15:04

标签: javascript graph

我有一个用cpettitt/graphlib定义的图表。

是否有任何简单的方法可以更改节点的ID以及更新任何边缘?

1 个答案:

答案 0 :(得分:0)

这是我的解决方案,使用新ID及其边缘创建节点的副本。然后删除旧节点。

changeId(current, newId) {
    let g = this.getGraph();

    // Change on graph
    let node = g.node(current);
    let inEdges = g.inEdges(current);
    let outEdges = g.outEdges(current);

    // Create new node
    node.id = newId;
    g.setNode(newId, node);
    // Create new edges
    for (let i = 0; i < inEdges.length; i++) {
        let edge = inEdges[i];
        let conn = g.edge(edge.v, current);
        conn.target = newId;
        g.setEdge(edge.v, newId, conn);
    }
    for (let i = 0; i < outEdges.length; i++) {
        let edge = outEdges[i];
        let conn = g.edge(current, edge.w);
        conn.source = newId;
        g.setEdge(newId, edge.w, conn);
    }
    // Remove old node
    g.removeNode(current);
}