使用treemodel.js合并两棵树

merging two trees using treemodel.js

本文关键字:两棵 treemodel js 合并 使用      更新时间:2023-09-26

示例:http://jsfiddle.net/yeehawjared/bawv0790/

我正在构建一个打开网页的应用程序,加载大型数据树结构的JSON。TreeModel.js解析了这个伟大的东西,一切都很好。

随着时间的推移,浏览器会以较小数据树的形式接收更新。我正试着把additionalDatamasterTree结合起来。我想不出一种方法可以同时遍历两者并进行逐节点比较。如果可以的话,聚合node.model.x属性并添加不存在的子项会很容易。

在下面的代码中,我浏览了额外的数据,但我不知道如何有效地将新节点组合到masterTree中。有人能用psuedo代码帮助我的方法论吗?或者为我指明正确的方向?持续更新masterTree的最佳方式是什么?

非常感谢。

var tree = new TreeModel();
var masterTree = tree.parse(data1);
var additionalData = tree.parse(data2);
additionalData.walk(function (node) {
    // compare additionalData to the masterTree
    if (node.model.id == masterTree.model.id) {
        console.debug('match, combine the attributes')
    } else {
        // add the additional node to the materTree
    }
});

看看这个小提琴的例子:http://jsfiddle.net/bawv0790/1/

重要的功能是mergeNodes。它是一个递归函数,接收两个节点,n1和n2。首先,它根据n2更新n1大小,并且如果缺少n2个子项,则将其添加到n1,或者如果存在则将其合并。

function mergeNodes(n1, n2) {
    var n1HasN2Child, i, n2Child;
    // Update the sizes
    updateSize(n1, n2);
    // Check which n2 children are present in n1
    n1HasN2Child = n2.children.map(hasChild(n1));
    // Iterate over n2 children
    for (i = 0; i < n1HasN2Child.length; i++) {
        n2Child = n2.children[i];
        if (n1HasN2Child[i]) {
            // n1 already has this n2 child, so lets merge them
            n1Child = n1.first({strategy: 'breadth'}, idEq(n2Child));
            mergeNodes(n1Child, n2Child);
        } else {
            // n1 does not have this n2 child, so add it
            n1.addChild(n2Child);
        }
    }
}

如果对孩子们进行分类,那么检查哪些n2个孩子在n1中可以得到极大的改进。