github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/commons/container/trees/convert_test.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package trees_test 19 20 import ( 21 "encoding/json" 22 "fmt" 23 "github.com/aacfactory/fns/commons/container/trees" 24 "testing" 25 ) 26 27 type Nodes []*Node 28 29 func (nodes Nodes) Len() int { 30 return len(nodes) 31 } 32 33 func (nodes Nodes) Less(i, j int) bool { 34 return nodes[i].Id < nodes[j].Id 35 } 36 37 func (nodes Nodes) Swap(i, j int) { 38 nodes[i], nodes[j] = nodes[j], nodes[i] 39 return 40 } 41 42 type Node struct { 43 Id string `tree:"Parent+Children"` 44 Parent string 45 Children Nodes 46 } 47 48 func TestConvertListToTree(t *testing.T) { 49 nodes := []Node{ 50 {Id: "C", Parent: "D"}, 51 {Id: "A", Parent: ""}, 52 {Id: "A2", Parent: "A"}, 53 {Id: "A1", Parent: "A"}, 54 {Id: "A12", Parent: "A1"}, 55 {Id: "A11", Parent: "A1"}, 56 {Id: "B1", Parent: "B"}, 57 {Id: "B1", Parent: "B"}, 58 {Id: "B", Parent: ""}, 59 } 60 v, treesErr := trees.ConvertListToTree[Node](nodes) 61 if treesErr != nil { 62 t.Errorf("%+v", treesErr) 63 return 64 } 65 p, err := json.MarshalIndent(v, "", "\t") 66 if err != nil { 67 t.Errorf("%+v", err) 68 return 69 } 70 fmt.Println(string(p)) 71 }