I am working with a tree structure made up of nodes called LayerNode
. Each node has references to its children and parent.
My goal is to update the property of a parent node if any of its child nodes have the property selected = true
.
public recursiveSelectLayers(node: LayerNode) {
if (node.children)
node.children.forEach((childNode: LayerNode) => {
childNode.parent = node;
if (childNode?.parent?.selected)
childNode.selected = childNode.parent.selected;
if (childNode.selected && childNode.parent)
childNode.parent.selected = childNode.selected;
this.recursiveSelectLayers(childNode);
});
}
Additionally, if a parent node is marked as selected
, all of its immediate children should also be set as selected
.
The issue arises when one of the children is selected, causing the function mentioned above to select all descendants from that child to the root node.
Upon reflecting on the situation, I made a second attempt:
public recursiveSelectLayers(node: LayerNode) {
if (node.parent && node.selected) node.parent.selected = node.selected;
if (node.children) {
node.children.forEach((childNode: LayerNode) => {
if (node?.selected) childNode.selected = node.selected;
childNode.parent = node;
this.recursiveSelectLayers(childNode);
});
}
}
Scenario 1:
Parent 1 (selected)
Child 1
Child 2
Child 3 (selected)
Scenario 2:
Parent 1 (selected)
Child 1 (selected)
Child 2 (selected)
Child 3 (selected)
Scenario 3:
Parent 1 (selected)
Child 1
Child 2
Child 3 (selected)
Child 3.1 (selected)
Update:
public recursiveSelectLayers(node: LayerNode) {
if (node.id) this.flatlayers.set(node.id, node);
if (node.children) {
node.children.forEach(this.recursiveSelectLayers, this);
node.selected =
[...node.children].some((node) => node.selected) ||
node?.parent?.selected;
}
}