Skip to content

Commit 200d676

Browse files
committed
Reduce duplication in onCheck/onExpand
1 parent d15e884 commit 200d676

File tree

1 file changed

+19
-26
lines changed

1 file changed

+19
-26
lines changed

src/js/Tree.js

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -39,28 +39,15 @@ class Tree extends React.Component {
3939
}
4040

4141
onCheck(node) {
42-
const checked = [...this.props.checked];
43-
const isChecked = node.checked;
42+
const { checked, onCheck } = this.props;
4443

45-
this.setCheckState(checked, node, isChecked);
46-
47-
this.props.onCheck(checked);
44+
onCheck(this.toggleChecked([...checked], node, node.checked));
4845
}
4946

5047
onExpand(node) {
51-
const isExpanded = node.expanded;
52-
const expanded = [...this.props.expanded];
53-
const nodeIndex = expanded.indexOf(node.value);
54-
55-
if (!isExpanded && nodeIndex > -1) {
56-
// Node is now collapsed, remove from expanded list
57-
expanded.splice(nodeIndex, 1);
58-
} else if (isExpanded && nodeIndex === -1) {
59-
// Add node to expanded list
60-
expanded.push(node.value);
61-
}
48+
const { expanded, onExpand } = this.props;
6249

63-
this.props.onExpand(expanded);
50+
onExpand(this.toggleNode([...expanded], node, node.expanded));
6451
}
6552

6653
getFormattedNodes(nodes) {
@@ -98,24 +85,30 @@ class Tree extends React.Component {
9885
return 0;
9986
}
10087

101-
setCheckState(checked, node, isChecked) {
88+
toggleChecked(checked, node, isChecked) {
10289
if (node.children !== null) {
10390
// Percolate check status down to all children
10491
node.children.forEach((child) => {
105-
this.setCheckState(checked, child, isChecked);
92+
this.toggleChecked(checked, child, isChecked);
10693
});
10794
} else {
10895
// Set leaf to check/unchecked state
109-
const index = checked.indexOf(node.value);
96+
this.toggleNode(checked, node, isChecked);
97+
}
11098

111-
if (index > -1) {
112-
checked.splice(index, 1);
113-
}
99+
return checked;
100+
}
114101

115-
if (isChecked) {
116-
checked.push(node.value);
117-
}
102+
toggleNode(list, node, toggleValue) {
103+
const index = list.indexOf(node.value);
104+
105+
if (index > -1 && !toggleValue) {
106+
list.splice(index, 1);
107+
} else if (index === -1 && toggleValue) {
108+
list.push(node.value);
118109
}
110+
111+
return list;
119112
}
120113

121114
isEveryChildChecked(node) {

0 commit comments

Comments
 (0)