package formattools import ( "fmt" "sort" "strings" ) func CompactMatch(ids []string) string { if len(ids) == 1 { return ids[0] } shortestPrefix := ids[0] for _, curr := range ids[1:] { minLength := len(shortestPrefix) if len(curr) < minLength { minLength = len(curr) } if len(shortestPrefix) > minLength { shortestPrefix = shortestPrefix[:minLength] } for i := 0; i < minLength; i++ { if curr[i] != shortestPrefix[i] { shortestPrefix = curr[:i] break } } } sb := strings.Builder{} sb.WriteString(shortestPrefix) sb.WriteByte('{') for i, curr := range ids { if i != 0 { sb.WriteByte(',') } sb.WriteString(curr[len(shortestPrefix):]) } sb.WriteByte('}') return sb.String() } func CompactIDList(ids []string) []string { ids = append(ids[:0:0], ids...) sort.Strings(ids) currentGroup := "" currentIDs := make([]string, 0, len(ids)) groups := make([]string, 0, 2) for _, id := range ids { if id == "" { continue } split := strings.SplitN(id, ":", 3) if len(split) < 3 { continue } group := id[:len(split[0])+len(split[1])+1] if group != currentGroup { if len(currentIDs) > 0 { if len(currentIDs) == 1 { groups = append(groups, fmt.Sprintf("%s:%s", currentGroup, currentIDs[0])) } else { groups = append(groups, fmt.Sprintf("%s:{%s}", currentGroup, strings.Join(currentIDs, ","))) } currentIDs = currentIDs[:0] } currentGroup = group } currentIDs = append(currentIDs, split[2]) } if len(currentIDs) > 0 { if len(currentIDs) == 1 { groups = append(groups, fmt.Sprintf("%s:%s", currentGroup, currentIDs[0])) } else { groups = append(groups, fmt.Sprintf("%s:{%s}", currentGroup, strings.Join(currentIDs, ","))) } } return groups }