1
1
class Tree {
2
- constructor ( component , useStateInstead = false ) {
2
+ constructor ( component , useStateInstead = false , name ) {
3
3
// special case when component is root
4
4
// give it a special state = 'root'
5
5
// a setState function that just calls the callback instantly
6
6
if ( ! useStateInstead ) {
7
7
this . component = ( component === 'root' ) ? { state : 'root' , setState : ( partial , callback ) => callback ( ) } : component ;
8
8
} else {
9
9
this . state = component ;
10
+ this . name = name ;
10
11
}
11
12
this . children = [ ] ;
12
13
}
@@ -18,9 +19,9 @@ class Tree {
18
19
}
19
20
20
21
// deep copies only the state of each component and creates a new tree
21
- getCopy ( copy = new Tree ( 'root' , true ) ) {
22
+ getCopy ( copy = new Tree ( 'root' , true , 'root' ) ) {
22
23
// copy state of children
23
- copy . children = this . children . map ( child => new Tree ( child . component . state , true ) ) ;
24
+ copy . children = this . children . map ( child => new Tree ( child . component . state , true , child . component . constructor . name ) ) ;
24
25
25
26
// copy children's children recursively
26
27
this . children . forEach ( ( child , i ) => child . getCopy ( copy . children [ i ] ) ) ;
@@ -31,10 +32,13 @@ class Tree {
31
32
print ( ) {
32
33
const children = [ 'children: ' ] ;
33
34
this . children . forEach ( ( child ) => {
34
- children . push ( child . component . state ) ;
35
+ children . push ( child . state || child . component . state ) ;
35
36
} ) ;
36
- if ( children . length === 1 ) console . log ( this . component . state ) ;
37
- else console . log ( this . component . state , ...children ) ;
37
+ if ( this . name ) console . log ( this . name ) ;
38
+ if ( children . length === 1 ) {
39
+ console . log ( this . state || this . component . state ) ;
40
+ }
41
+ else console . log ( this . state || this . component . state , ...children ) ;
38
42
this . children . forEach ( ( child ) => {
39
43
child . print ( ) ;
40
44
} ) ;
0 commit comments