Skip to content

Commit

Permalink
✨ Add func for split dir with slash (#165)
Browse files Browse the repository at this point in the history
  • Loading branch information
tosone authored Aug 2, 2023
1 parent b5e3245 commit 67def8a
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 0 deletions.
22 changes: 22 additions & 0 deletions pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,25 @@ func MustMarshal(in any) []byte {
}
return result
}

// DirWithSlash returns the dir with slash
func DirWithSlash(id string) string {
// judge if the string has two slashes
if len(strings.Split(id, "/")) == 3 {
return id
}
if len(id) > 2 {
if !strings.Contains(id, "/") {
return DirWithSlash(fmt.Sprintf("%s/%s", id[0:2], id[2:]))
}
// remove the str before the last slash
str := id[strings.LastIndex(id, "/")+1:]
if len(str) > 2 {
str = fmt.Sprintf("%s/%s", str[0:2], str[2:])
} else {
return fmt.Sprintf("%s/%s", strings.TrimSuffix(id[0:strings.LastIndex(id, "/")+1], "/"), str)
}
return DirWithSlash(fmt.Sprintf("%s/%s", strings.TrimSuffix(id[0:strings.LastIndex(id, "/")+1], "/"), str))
}
return id
}
68 changes: 68 additions & 0 deletions pkg/utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,71 @@ func TestIsExist(t *testing.T) {
})
})
}

func TestDirWithSlash(t *testing.T) {
type args struct {
id string
}
tests := []struct {
name string
args args
want string
}{
{
name: "common",
args: args{
id: "",
},
want: "",
},
{
name: "common",
args: args{
id: "1",
},
want: "1",
},
{
name: "common",
args: args{
id: "12",
},
want: "12",
},
{
name: "common",
args: args{
id: "123",
},
want: "12/3",
},
{
name: "common",
args: args{
id: "1234",
},
want: "12/34",
},
{
name: "common",
args: args{
id: "12345",
},
want: "12/34/5",
},
{
name: "common",
args: args{
id: "123456789",
},
want: "12/34/56789",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := DirWithSlash(tt.args.id); got != tt.want {
t.Errorf("DirWithSlash() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 67def8a

Please sign in to comment.