|
| 1 | +package unpackerr |
| 2 | + |
| 3 | +import ( |
| 4 | + "strconv" |
| 5 | + "strings" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +const ( |
| 10 | + durationPartsLimit = 3 |
| 11 | + daysPerWeek = 7 |
| 12 | + daysPerYear = 365 |
| 13 | + hoursPerDay = 24 |
| 14 | +) |
| 15 | + |
| 16 | +func formatDuration(duration time.Duration) string { |
| 17 | + duration = duration.Abs() |
| 18 | + units := []struct { |
| 19 | + name string |
| 20 | + duration time.Duration |
| 21 | + }{ |
| 22 | + {name: "year", duration: daysPerYear * hoursPerDay * time.Hour}, |
| 23 | + {name: "week", duration: daysPerWeek * hoursPerDay * time.Hour}, |
| 24 | + {name: "day", duration: hoursPerDay * time.Hour}, |
| 25 | + {name: "hour", duration: time.Hour}, |
| 26 | + {name: "minute", duration: time.Minute}, |
| 27 | + {name: "second", duration: time.Second}, |
| 28 | + {name: "millisecond", duration: time.Millisecond}, |
| 29 | + {name: "microsecond", duration: time.Microsecond}, |
| 30 | + } |
| 31 | + |
| 32 | + parts := make([]string, 0, durationPartsLimit) |
| 33 | + remaining := duration |
| 34 | + |
| 35 | + for _, unit := range units { |
| 36 | + count := int64(remaining / unit.duration) |
| 37 | + if count == 0 { |
| 38 | + continue |
| 39 | + } |
| 40 | + |
| 41 | + parts = append(parts, formatDurationPart(count, unit.name)) |
| 42 | + remaining -= time.Duration(count) * unit.duration |
| 43 | + |
| 44 | + if len(parts) == durationPartsLimit { |
| 45 | + break |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + if len(parts) == 0 { |
| 50 | + return "0 seconds" |
| 51 | + } |
| 52 | + |
| 53 | + return strings.Join(parts, " ") |
| 54 | +} |
| 55 | + |
| 56 | +func formatDurationPart(count int64, name string) string { |
| 57 | + if count == 1 { |
| 58 | + return strconv.FormatInt(count, 10) + " " + name |
| 59 | + } |
| 60 | + |
| 61 | + return strconv.FormatInt(count, 10) + " " + name + "s" |
| 62 | +} |
0 commit comments