How to get a modified tree from an immutable tree, maximizing node reuse

I have tree structure data:

[{
    id: 54,
    name:123,
    children: [{
        id: 54,
        name:123,
        children: [{
            id: 154,
            name:1234,
            children []...
        }]
    }]
}, {
 ...
}]

I am using Angular 2. As far as I know, change the detected hits every time you change the input and change detection strategy onPush.

To optimize tree structure updates (for example, by switching a node at a nested level or changing any attributes of such a node), I used Immutable .

As indispensable help me optimize my updates? I read that Immutable reuses references from old data to create new objects when data changes.

?

  • keyPath .
  • node id, ( ?)

  • node - ? node?
  • ? API withMutations, ?

  • , :

    var newState = deepClone(oldState) // deep copy everything and construct a new object 
    newState.nodes.forEach(node => {
        if(node.id == 54) {
            node.id = 789;
        }
    })
    
  • :

    var newState = Immutable.fromJS(oldState) // create an immutable object 
    newState = newState.find(node => {
        node.set("id", 123);
    }); // any changes to object will return new object
    

, :

Tree view in immutablejs

+4
1

, , Immutable , node, node, , , .

: , , node. , node , , , ( children ). , , node,... .. node, , , , node.

, - :

enter image description here

The Immutable API updateIn method ( setIn, node). () node, .

, , , , node , , node.

function findKeyPathOf(tree, childrenKey, predicate) {
    var path;
    if (Immutable.List.isList(tree)) {
        tree.some(function (child, i) {
            path = findKeyPathOf(child, childrenKey, predicate);
            if (path) return path.unshift(i); // always returns truthy
        });
        return path;
    } 
    if (predicate(tree)) return [];
    path = findKeyPathOf(tree.get(childrenKey), childrenKey, predicate);
    if (path) return [childrenKey].concat(path);
}

, , ( children ), , node, . , , node id 4, :

var keyPath = findKeyPathOf(tree, 'children', node => node.get('id') == 4);

: children, :

[0, 'children', 0, 'children', 1]

, node , - :

var newTree = tree.updateIn(keyPath, node => node.set('name', 'Hello'));

:

// Function to get the path to a certain node in the tree
function findKeyPathOf(tree, childrenKey, predicate) {
    var path;
    if (Immutable.List.isList(tree))
        childrenKey = tree.findKey(child =>
            path = findKeyPathOf(child, childrenKey, predicate));
    else if (predicate(tree)) 
        return [];
    else
        path = findKeyPathOf(tree.get(childrenKey), childrenKey, predicate);
    return path && [childrenKey].concat(path);
}

// Function to compare two trees
function differences(tree1, tree2, childrenKey) {
    if (Immutable.List.isList(tree1)) {
        return tree1.reduce(function (diffs, child, i) {
            return diffs.concat(differences(child, tree2.get(i), childrenKey));
        }, []);
    }
    return (tree1 !== tree2 ? [tree1] : []) 
        .concat(differences(tree1.get(childrenKey), tree2.get(childrenKey),
                            childrenKey));
}

// Sample data
var tree = [{
    id: 1,
    name: 'Mike',
    children: [{
        id: 2,
        name: 'Helen',
        children: [{
            id: 3,
            name: 'John',
            children: []
        },{
            id: 4,
            name: 'Sarah',
            children: [{
                id: 5,
                name: 'Joy',
                children: []
            }]
        }]
    }]
}, {
    id: 6,
    name: 'Jack',
    children: [{
        id: 7,
        name: 'Irene',
        children: []
    },{
        id: 8,
        name: 'Peter',
        children: []
    }]
}];

// Create immutable tree from above plain object:
var tree = Immutable.fromJS(tree);

// Use the function to find the node with id == 4:
var keyPath = findKeyPathOf(tree, 'children', node => node.get('id') == 4);

// Found it?
if (keyPath) {
    // Set 'name' to 'Hello' in that node:
    var newTree = tree.updateIn(keyPath, node => node.set('name', 'Hello'));
    // Print the new tree:
    console.log(newTree.toJS());
    // Compare all nodes to see which ones were altered:
    var altered = differences(tree, newTree, 'children').map(x => x.get('id'));
    console.log('IDs of nodes that were replaced: ', altered);
} else {
    console.log('Not found!');
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.min.js"></script>
+4

Source: https://habr.com/ru/post/1664654/


All Articles