Created
June 17, 2020 18:00
-
-
Save overdrive3000/6cb347764885ecb7625a219e4100375c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package clock mocks a simple clock which only | |
// supports hours and minutes and basic add, sub | |
// operations in minutes. | |
package clock | |
import ( | |
"fmt" | |
) | |
// day number of minutes in a day | |
const day = 1440 | |
// Clock represents a Clock object that only | |
// handle hours and minutes | |
type Clock struct { | |
Hour int | |
Minute int | |
} | |
// New constructor return a new Clock object | |
func New(h, m int) Clock { | |
return setClock(h, m) | |
} | |
func setClock(h, m int) Clock { | |
minutes := (60 * h) + m | |
for minutes < 0 { | |
minutes += day | |
} | |
for minutes >= day { | |
minutes -= day | |
} | |
return Clock{ | |
Hour: int(minutes / 60), | |
Minute: minutes % 60, | |
} | |
} | |
// String returns an string representation | |
// of the hours in the following format 00h:00m | |
func (c Clock) String() string { | |
return fmt.Sprintf("%02d:%02d", c.Hour, c.Minute) | |
} | |
// Add return hour by adding give m (minute) | |
func (c Clock) Add(m int) Clock { | |
c.Minute += m | |
return setClock(c.Hour, c.Minute) | |
} | |
// Subtract return hour by substracting given m (minute) | |
func (c Clock) Subtract(m int) Clock { | |
c.Minute -= m | |
return setClock(c.Hour, c.Minute) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment