少し変更
package main
import (
"fmt"
"path"
"strings"
)
type File struct {
Id string
Name string
}
type Folder struct {
Name string
Files []File
Folders map[string]*Folder
}
func newFolder(name string) *Folder {
return &Folder{name, []File{}, make(map[string]*Folder)}
}
func (f *Folder) getFolder(name string) *Folder {
if nextF, ok := f.Folders[name]; ok {
return nextF
} else if f.Name == name {
return f
} else {
return &Folder{}
}
}
func (f *Folder) existFolder(name string) bool {
for _, v := range f.Folders {
if v.Name == name {
return true
}
}
return false
}
func (f *Folder) addFolder(folderName string) {
if !f.existFolder(folderName) {
f.Folders[folderName] = newFolder(folderName)
}
}
func (f *Folder) addFile(fileName string, fileId string) {
f.Files = append(f.Files, File{fileId, fileName})
}
func (f *Folder) getList() (result []map[string]interface{}) {
for _, v := range f.Folders {
result = append(result, map[string]interface{}{
"name": v.Name,
"type": "folder",
})
}
for _, v := range f.Files {
result = append(result, map[string]interface{}{
"id": v.Id,
"name": v.Name,
"type": "file",
})
}
return
}
func isFile(str string) bool {
if path.Ext(str) != "" {
return true
}
return false
}
func DeleteEmptyElements(s []string) []string {
var r []string
for _, str := range s {
if str != "" {
r = append(r, str)
}
}
return r
}
type IS map[string]string
func main() {
arrayPaths := []interface{}{
IS{
"id": "1",
"filePath": "/print/some/com.png",
},
IS{
"id": "2",
"filePath": "/print/some2/com412412.png",
},
IS{
"id": "3",
"filePath": "/print/some2/41241241241.png",
},
}
breadcrumb := "/print/some2"
startPath := "/"
rootFolder := newFolder(startPath)
for _, path := range arrayPaths {
filePath := path.(IS)["filePath"]
fileId := path.(IS)["id"]
splitPath := DeleteEmptyElements(strings.Split(filePath, "/"))
tmpFolder := rootFolder
for _, item := range splitPath {
if isFile(item) {
tmpFolder.addFile(item, fileId)
} else {
if item != startPath {
tmpFolder.addFolder(item)
}
tmpFolder = tmpFolder.getFolder(item)
}
}
}
currentFolder := rootFolder.getFolder("/")
breadcrumbElements := DeleteEmptyElements(strings.Split(breadcrumb, "/"))
for i, v := range breadcrumbElements {
if currentFolder.existFolder(v) {
currentFolder = currentFolder.getFolder(v)
if i == len(breadcrumbElements)-1 {
break
}
} else {
currentFolder = currentFolder.getFolder(v)
}
}
fmt.Println(currentFolder.getList())
}