1
1
class Tree {
2
- constructor ( component ) {
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
- this . component = ( component === 'root' ) ? { state : 'root' , setState : ( partial , callback ) => callback ( ) } : component ;
6
+ if ( ! useStateInstead ) {
7
+ this . component = ( component === 'root' ) ? { state : 'root' , setState : ( partial , callback ) => callback ( ) } : component ;
8
+ } else {
9
+ this . state = component ;
10
+ this . name = name ;
11
+ }
7
12
this . children = [ ] ;
8
13
}
9
14
@@ -14,12 +19,9 @@ class Tree {
14
19
}
15
20
16
21
// deep copies only the state of each component and creates a new tree
17
- getCopy ( copy = new Tree ( null ) ) {
18
- const { state } = this . component ;
19
- if ( ! copy . component ) copy . component = { state } ;
20
-
22
+ getCopy ( copy = new Tree ( 'root' , true , 'root' ) ) {
21
23
// copy state of children
22
- copy . children = this . children . map ( child => new Tree ( { state : child . component . state } ) ) ;
24
+ copy . children = this . children . map ( child => new Tree ( child . component . state , true , child . component . constructor . name ) ) ;
23
25
24
26
// copy children's children recursively
25
27
this . children . forEach ( ( child , i ) => child . getCopy ( copy . children [ i ] ) ) ;
@@ -30,10 +32,13 @@ class Tree {
30
32
print ( ) {
31
33
const children = [ 'children: ' ] ;
32
34
this . children . forEach ( ( child ) => {
33
- children . push ( child . component . state ) ;
35
+ children . push ( child . state || child . component . state ) ;
34
36
} ) ;
35
- if ( children . length === 1 ) console . log ( this . component . state ) ;
36
- 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 ) ;
37
42
this . children . forEach ( ( child ) => {
38
43
child . print ( ) ;
39
44
} ) ;
0 commit comments