tree.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package tree
  2. type Node[T any] struct {
  3. Value T `json:"value"`
  4. Children []Node[T] `json:"children"`
  5. }
  6. func SetChildren[T any](node *Node[T], getChildValues func(node *Node[T]) ([]T, error)) error {
  7. childValues, err := getChildValues(node)
  8. if err != nil {
  9. return err
  10. }
  11. if len(childValues) == 0 {
  12. node.Children = nil
  13. return nil
  14. }
  15. childNodes := make([]Node[T], 0)
  16. for _, childValue := range childValues {
  17. childNode := Node[T]{
  18. Value: childValue,
  19. }
  20. err := SetChildren[T](&childNode, getChildValues)
  21. if err != nil {
  22. return err
  23. }
  24. childNodes = append(childNodes, childNode)
  25. }
  26. node.Children = childNodes
  27. return nil
  28. }
  29. func QueryTree[I, V any](
  30. input I,
  31. getRoots func(inputMsg I) ([]V, error),
  32. getChildren func(e *V) ([]V, error),
  33. ) ([]Node[V], error) {
  34. //顶部
  35. nRootValues, err := getRoots(input)
  36. if err != nil {
  37. return nil, err
  38. }
  39. //里面
  40. rootNodeSlice := make([]Node[V], 0)
  41. for _, nRootValue := range nRootValues {
  42. nRoot := Node[V]{
  43. Value: nRootValue,
  44. }
  45. err := SetChildren[V](&nRoot, func(node *Node[V]) ([]V, error) {
  46. nChildValues, err := getChildren(&node.Value)
  47. if err != nil {
  48. return nil, err
  49. }
  50. if len(nChildValues) == 0 {
  51. node.Children = nil
  52. return nil, nil
  53. }
  54. result := make([]V, 0)
  55. for _, nChildValue := range nChildValues {
  56. result = append(result, nChildValue)
  57. }
  58. return result, nil
  59. })
  60. if err != nil {
  61. return nil, err
  62. }
  63. rootNodeSlice = append(rootNodeSlice, nRoot)
  64. }
  65. return rootNodeSlice, nil
  66. }