inits.go 843 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. }