通用包
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
utils/pkg/tree/tree.go

55 lines
1.1 KiB

2 years ago
package tree
2 years ago
2 years ago
import (
"regexp"
)
2 years ago
type Node[T any] struct {
2 years ago
Data T `json:"data"`
Children []Node[T] `json:"children"`
2 years ago
}
2 years ago
func Length(code string) int {
re := regexp.MustCompile(`[A-Z]\d+`)
match := re.FindString(code)
return len(match)
}
2 years ago
// 适用 A00001B00001 层级结构
// parent 父级字符串
// length A00001 一个节点长度
// pathFunc 返回T的code A00001
func Tree[T any](data []T, parent string, length int, pathFunc func(d T) string) (res []Node[T]) {
for _, v := range data {
path := pathFunc(v)
if len(path) < length {
2 years ago
return
2 years ago
}
p := path[:len(path)-length]
if p == parent {
res = append(res, Node[T]{
Data: v,
Children: Tree[T](data, path, length, pathFunc),
})
}
}
return
}
2 years ago
// 拆分层级结构 A00001B00001C00001 拆分为 ["A00001","A00001B00001","A00001B00001C00001"]
2 years ago
func Split(code string) (res []string) {
if code == "" {
return []string{}
}
l := Length(code)
if len(code) < l {
2 years ago
return
}
2 years ago
times := len(code) / l
2 years ago
for i := 0; i < times; i++ {
2 years ago
res = append(res, code[:len(code)-l*i])
2 years ago
}
return
}