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.

52 lines
843 B

  1. package util
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. // HumanReadableIntsMax joins a serials of inits into a smart one like 1-3 5 ... for human readable.
  7. func HumanReadableIntsMax(max int, ids ...int) string {
  8. if len(ids) <= max {
  9. return HumanReadableInts(ids...)
  10. }
  11. return HumanReadableInts(ids[:max]...) + " ..."
  12. }
  13. // HumanReadableInts joins a serials of inits into a smart one like 1-3 5 7-10 for human readable.
  14. func HumanReadableInts(ids ...int) string {
  15. sort.Ints(ids)
  16. s := ""
  17. start := 0
  18. last := 0
  19. for i, v := range ids {
  20. if i == 0 {
  21. start = v
  22. last = v
  23. s = fmt.Sprintf("%d", v)
  24. continue
  25. }
  26. if last+1 == v {
  27. last = v
  28. continue
  29. }
  30. if last > start {
  31. s += fmt.Sprintf("-%d", last)
  32. }
  33. s += fmt.Sprintf(" %d", v)
  34. start = v
  35. last = v
  36. }
  37. if last != start {
  38. s += fmt.Sprintf("-%d", last)
  39. }
  40. return s
  41. }