Keytree
Keytree is a library that helps you to transfer flatten key slice to cascade key tree.
Flatten key slice (before transfer):
a
a/ // item and dir with same name
a/dir1/ // empty dir
a/dir2/item3 // item without parent dir
a/item
a/item2
a1/
b/
b/dir3/
b/dir3/item4
Key tree (after transfer):
[
{
"name": "a",
"type": "dir",
"children": [
{
"name": "dir1",
"type": "dir",
"isLeaf": false
},
{
"name": "dir2",
"type": "dir",
"children": [
{
"name": "item3",
"type": "item",
"isLeaf": true
}
],
"isLeaf": false
},
{
"name": "item1",
"type": "item",
"isLeaf": true
},
{
"name": "item2",
"type": "item",
"isLeaf": true
}
],
"isLeaf": false
},
{
"name": "a1",
"type": "dir",
"isLeaf": false
},
{
"name": "b",
"type": "dir",
"children": [
{
"name": "dir3",
"type": "dir",
"children": [
{
"name": "item4",
"type": "item",
"isLeaf": true
}
],
"isLeaf": false
}
],
"isLeaf": false
},
{
"name": "a",
"type": "item",
"isLeaf": true
}
]
Usage
- Transfer
[]string
to KeyMap
(unordered but have unique key index)
keyMap := keytree.BuildMap(keys)
Each key with a slash suffix (like a/
) represents a "directory".
Keys without parent directory (like a/dir2/item3
above) will be fixed by adding missing "parent".
The JSON form of keyMap
is shown below. If you print keyMap
, the result may be different in key sequence because map is unordered.
{
"a": null,
"a/": {
"dir1/": {},
"dir2/": {
"item3": null
},
"item1": null,
"item2": null
},
"a1/": {},
"b/": {
"dir3/": {
"item4": null
}
}
}
- Transfer
KeyMap
to KeyList
(ordered but have no key index)
keyList := keytree.BuildKeyListFromMap(keyMap)
The JSON form of keyList
is shown at the top. It's ordered.
Frontend Friendly
The result KeyList
json could be directly passed to the data
field of frontend tree components.
Supported frontend tree modules:
- Vue
el-tree
- Ant Design
Tree
Unsupported Keys
If you use this library in Consul
or Etcd
, note that their keys are NOT strictly cascaded. You should exclude some special keys such as
- empty string
""
- slash
"/"
- key with 2 or more continous slash (like
"a//b"
)
License
The license is switched from GPLv3 to MulanPSL-2.0 (v0.1.1
and after), with a supplementary note file to fill the license template.