Skip to content

Instantly share code, notes, and snippets.

@pca2
Created February 24, 2019 18:38
Show Gist options
  • Save pca2/0df72da8efa0f162e182148028d55133 to your computer and use it in GitHub Desktop.
Save pca2/0df72da8efa0f162e182148028d55133 to your computer and use it in GitHub Desktop.
package clock
import (
"fmt"
)
type clock struct {
hour int
minute int
}
func New(hour, minute int ) clock {
hour, minute = build(hour, minute)
return clock{hour:hour, minute:minute}
}
func (c clock) String() string {
return fmt.Sprintf("%02d:%02d", c.hour, c.minute)
}
func (c clock) Add(minutes int ) clock {
c.hour, c.minute = build(c.hour, c.minute + minutes)
return c
}
func (c clock) Subtract(minutes int ) clock {
c.hour, c.minute = build(c.hour, c.minute - minutes)
return c
}
func build(h, m int) (int, int) {
h += m / 60
m %= 60
if m < 0 {
m += 60
h -= 1
}
h %= 24
if h < 0 {
h += 24
}
return h, m
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment