增加生成新节点的方法

This commit is contained in:
2023-03-28 23:56:13 +08:00
parent 055c833fce
commit f24fe13e4b
3 changed files with 137 additions and 2 deletions

View File

@ -7,6 +7,12 @@
// Date : 2023-03-28 18:12
package tree
import (
"strings"
"git.zhangdeman.cn/zhangdeman/util"
)
// Node 节点的数据结构
//
// Author : go_developer@163.com<白茶清欢>
@ -27,3 +33,70 @@ type Node struct {
LastBrotherNode *Node // 下一个兄弟节点
SonNodeList []*Node // 子节点列表
}
// NewNode 创建新节点
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 23:02 2023/3/28
func NewNode(key string, value string, valueType string, parentNode *Node) *Node {
n := &Node{
IsVirtual: false,
Value: value,
ValueType: valueType,
Key: key,
Show: false,
ShowKey: "",
AllowEdit: false,
AllowChangeType: false,
DefaultValue: nil,
ParentNode: parentNode,
PreBrotherNode: nil,
LastBrotherNode: nil,
SonNodeList: nil,
}
switch valueType {
case ValueTypeString:
n.Value = value
case ValueTypeInteger:
var v int64
_ = util.ConvertAssign(&v, value)
n.Value = v
case ValueTypeFloat:
var v float64
_ = util.ConvertAssign(&v, value)
n.Value = v
case ValueTypeBool:
n.Value = strings.ToLower(value) == "true"
case ValueTypeMap:
n.Value = map[string]interface{}{}
n.SonNodeList = make([]*Node, 0)
case ValueTypeArray:
n.Value = []interface{}{}
n.SonNodeList = make([]*Node, 0)
}
// 处理 preBrother 和 lastBrother
if parentNode.ValueType == ValueTypeMap || parentNode.ValueType == ValueTypeArray {
// map 和 array 才有所谓的兄弟节点
if len(parentNode.SonNodeList) > 0 {
// 设置新节点的 pre 节点
n.PreBrotherNode = parentNode.SonNodeList[len(parentNode.SonNodeList)-1]
// 设置当前最后一个节点的 last 节点
parentNode.SonNodeList[len(parentNode.SonNodeList)-1].LastBrotherNode = n
}
// 新节点追加到子节点末尾
parentNode.SonNodeList = append(parentNode.SonNodeList, n)
}
return n
}
// NewVirtualNode 创建一个新的虚拟节点
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 23:08 2023/3/28
func NewVirtualNode() *Node {
return &Node{IsVirtual: true, SonNodeList: make([]*Node, 0)}
}