Exercism: Go version of the 'Clock' exercise.
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.

45 lines
1.3 KiB

  1. // Package clock represents a dateless time of day.
  2. package clock
  3. import "fmt"
  4. const (
  5. testVersion = 3
  6. minutesPerHour = 60
  7. minutesPerDay = 1440
  8. )
  9. // A Clock stores a minute value representing a time of day.
  10. type Clock int
  11. // String returns an hour:minute representation of the Clock.
  12. func (c Clock) String() string {
  13. return fmt.Sprintf("%02d:%02d", c/minutesPerHour, c%minutesPerHour)
  14. }
  15. // Add returns a Clock adjusted by the number of minutes specified.
  16. func (c Clock) Add(minutes int) Clock {
  17. return parseTime(0, int(c)+minutes)
  18. }
  19. // New returns a Clock constructed from the given hour and minute values.
  20. func New(hour, minutes int) Clock {
  21. return parseTime(hour, minutes)
  22. }
  23. // parseTime computes the number of minutes that represent the time.
  24. func parseTime(hour, minutes int) Clock {
  25. // Compute the total minutes, factoring away multiple day values.
  26. total := (hour*minutesPerHour + minutes) % minutesPerDay
  27. // If total minutes is negative, roll forward one day.
  28. if total < 0 {
  29. total += minutesPerDay
  30. }
  31. return Clock(total)
  32. }
  33. // Benchmark versus previous iteration:
  34. //
  35. // benchmark old ns/op new ns/op delta
  36. // BenchmarkAddMinutes-12 45.7 29.7 -35.01%
  37. // BenchmarkCreateClocks-12 52.1 33.9 -34.93%