Skip to content

Commit a018a45

Browse files
committed
Patches findTargetNode to support arbitrary depth recursion
1 parent d380992 commit a018a45

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

src/Tree/index.js

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export default class Tree extends React.Component {
1616
data: this.assignInternalProperties(clone(this.props.data)),
1717
zoom: undefined,
1818
};
19-
this.findTargetNode = this.findTargetNode.bind(this);
19+
this.findNodesById = this.findNodesById.bind(this);
2020
this.collapseNode = this.collapseNode.bind(this);
2121
this.handleNodeToggle = this.handleNodeToggle.bind(this);
2222
}
@@ -100,29 +100,31 @@ export default class Tree extends React.Component {
100100

101101

102102
/**
103-
* findTargetNode - Recursively walks a set of nodes (`nodeSet`) and its
104-
* children until a `node.id` that matches `nodeId` param is found.
103+
* findNodesById - Description
105104
*
106-
* @param {string} nodeId The `node.id` being searched for
105+
* @param {string} nodeId The `node.id` being searched for
107106
* @param {array} nodeSet Array of `node` objects
107+
* @param {array} hits Accumulator for matches, passed between recursive calls
108108
*
109-
* @return {object} Returns the targeted `node` object
109+
* @return {array} Set of nodes matching `nodeId`
110110
*/
111111
// TODO Refactor this into a more readable/reasonable recursive depth-first walk.
112-
findTargetNode(nodeId, nodeSet) {
113-
const hits = nodeSet.filter((node) => node.id === nodeId);
114-
112+
findNodesById(nodeId, nodeSet, hits) {
115113
if (hits.length > 0) {
116-
const targetNode = hits[0];
117-
return targetNode;
114+
return hits;
118115
}
119116

120-
return nodeSet.map((node) => {
117+
hits = hits.concat(nodeSet.filter((node) => node.id === nodeId));
118+
119+
nodeSet.forEach((node) => {
121120
if (node._children && node._children.length > 0) {
122-
return this.findTargetNode(nodeId, node._children);
121+
hits = this.findNodesById(nodeId, node._children, hits);
122+
return hits;
123123
}
124-
return null;
125-
})[0];
124+
return hits;
125+
});
126+
127+
return hits;
126128
}
127129

128130

@@ -169,7 +171,8 @@ export default class Tree extends React.Component {
169171
handleNodeToggle(nodeId) {
170172
if (this.props.collapsible) {
171173
const data = clone(this.state.data);
172-
const targetNode = this.findTargetNode(nodeId, data);
174+
const matches = this.findNodesById(nodeId, data, []);
175+
const targetNode = matches[0];
173176
targetNode._collapsed
174177
? this.expandNode(targetNode)
175178
: this.collapseNode(targetNode);

0 commit comments

Comments
 (0)