使用treemodel.js合并两棵树

时间:2014-10-10 21:32:18

标签: javascript performance tree treemodel

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

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

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

在下面的代码中,我将介绍其他数据 - 但我不知道如何有效地将新节点组合到masterTree。有人可以用伪代码帮助我的方法,还是指向正确的方向?什么是不断更新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
    }
});

1 个答案:

答案 0 :(得分:3)

看一下这个小提琴,看看实际的例子:http://jsfiddle.net/bawv0790/1/

重要的功能是mergeNodes。它是一个递归函数,接收2个节点,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中可以大大改善。