You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.7 KiB

2 years ago
2 years ago
2 years ago
2 years ago
  1. package formattools
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. )
  7. func CompactMatch(ids []string) string {
  8. if len(ids) == 1 {
  9. return ids[0]
  10. }
  11. shortestPrefix := ids[0]
  12. for _, curr := range ids[1:] {
  13. minLength := len(shortestPrefix)
  14. if len(curr) < minLength {
  15. minLength = len(curr)
  16. }
  17. if len(shortestPrefix) > minLength {
  18. shortestPrefix = shortestPrefix[:minLength]
  19. }
  20. for i := 0; i < minLength; i++ {
  21. if curr[i] != shortestPrefix[i] {
  22. shortestPrefix = curr[:i]
  23. break
  24. }
  25. }
  26. }
  27. sb := strings.Builder{}
  28. sb.WriteString(shortestPrefix)
  29. sb.WriteByte('{')
  30. for i, curr := range ids {
  31. if i != 0 {
  32. sb.WriteByte(',')
  33. }
  34. sb.WriteString(curr[len(shortestPrefix):])
  35. }
  36. sb.WriteByte('}')
  37. return sb.String()
  38. }
  39. func CompactIDList(ids []string) []string {
  40. ids = append(ids[:0:0], ids...)
  41. sort.Strings(ids)
  42. currentGroup := ""
  43. currentIDs := make([]string, 0, len(ids))
  44. groups := make([]string, 0, 2)
  45. for _, id := range ids {
  46. if id == "" {
  47. continue
  48. }
  49. split := strings.SplitN(id, ":", 3)
  50. if len(split) < 3 {
  51. continue
  52. }
  53. group := id[:len(split[0])+len(split[1])+1]
  54. if group != currentGroup {
  55. if len(currentIDs) > 0 {
  56. if len(currentIDs) == 1 {
  57. groups = append(groups, fmt.Sprintf("%s:%s", currentGroup, currentIDs[0]))
  58. } else {
  59. groups = append(groups, fmt.Sprintf("%s:{%s}", currentGroup, strings.Join(currentIDs, ",")))
  60. }
  61. currentIDs = currentIDs[:0]
  62. }
  63. currentGroup = group
  64. }
  65. currentIDs = append(currentIDs, split[2])
  66. }
  67. if len(currentIDs) > 0 {
  68. if len(currentIDs) == 1 {
  69. groups = append(groups, fmt.Sprintf("%s:%s", currentGroup, currentIDs[0]))
  70. } else {
  71. groups = append(groups, fmt.Sprintf("%s:{%s}", currentGroup, strings.Join(currentIDs, ",")))
  72. }
  73. }
  74. return groups
  75. }