Skip to content

Commit

Permalink
style: optimize tags
Browse files Browse the repository at this point in the history
  • Loading branch information
tr1v3r committed Apr 10, 2024
1 parent b589b71 commit 15b9219
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions field/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"strings"
)

// TODO implement unit tests for tags

const (
TagKeyGorm = "gorm"
TagKeyJson = "json"
Expand Down Expand Up @@ -60,7 +62,7 @@ func (tag Tag) Build() string {
}

tags := make([]string, 0, len(tag))
for _, k := range tagKeys(tag) {
for _, k := range tag.keys() {
v := tag[k]
if k == "" {
continue
Expand All @@ -70,6 +72,18 @@ func (tag Tag) Build() string {
return strings.Join(tags, " ")
}

func (tag Tag) keys() []string {
if len(tag) == 0 {
return nil
}

keys := make([]string, 0, len(tag))
for k := range tag {
keys = append(keys, k)
}
return keySort(keys)
}

type GormTag map[string][]string

func (tag GormTag) Append(key string, values ...string) GormTag {
Expand All @@ -95,8 +109,9 @@ func (tag GormTag) Build() string {
if len(tag) == 0 {
return ""
}

tags := make([]string, 0, len(tag))
for _, k := range gormKeys(tag) {
for _, k := range tag.keys() {
vs := tag[k]
if len(vs) == 0 && k == "" {
continue
Expand All @@ -123,22 +138,12 @@ func (tag GormTag) Build() string {
return strings.Join(tags, ";")
}

func tagKeys(tag Tag) []string {
keys := make([]string, 0, len(tag))
func (tag GormTag) keys() []string {
if len(tag) == 0 {
return keys
}
for k := range tag {
keys = append(keys, k)
return nil
}
return keySort(keys)
}

func gormKeys(tag GormTag) []string {
keys := make([]string, 0, len(tag))
if len(tag) == 0 {
return keys
}
for k := range tag {
keys = append(keys, k)
}
Expand All @@ -149,6 +154,7 @@ func keySort(keys []string) []string {
if len(keys) == 0 {
return keys
}

sort.Slice(keys, func(i, j int) bool {
if tagKeyPriorities[keys[i]] == tagKeyPriorities[keys[j]] {
return keys[i] <= keys[j]
Expand Down

0 comments on commit 15b9219

Please sign in to comment.