From 26834e8d2b759cefc63174e27a5c72f6ff55d655 Mon Sep 17 00:00:00 2001 From: nikkiing <1031497516@qq.com> Date: Thu, 16 Mar 2023 14:33:38 +0800 Subject: [PATCH] pkg --- pkg/tree.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 pkg/tree.go diff --git a/pkg/tree.go b/pkg/tree.go new file mode 100644 index 0000000..aaf13be --- /dev/null +++ b/pkg/tree.go @@ -0,0 +1,27 @@ +package pkg + +type Node[T any] struct { + Data T + Children []Node[T] +} + +// 适用 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 { + return nil + } + p := path[:len(path)-length] + if p == parent { + res = append(res, Node[T]{ + Data: v, + Children: Tree[T](data, path, length, pathFunc), + }) + } + } + return +}