Last active
March 27, 2024 17:04
-
-
Save farhaduneci/3f8b8731054006d8fbd7b13b06d1b632 to your computer and use it in GitHub Desktop.
Simple Clock Struct Written in Go
This file contains hidden or 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 main | |
import ( | |
"fmt" | |
) | |
type Clock struct { | |
hours int | |
minutes int | |
} | |
func New(hours, minutes int) Clock { | |
h := (hours + minutes/60) % 24 | |
m := minutes % 60 | |
if m < 0 { | |
m += 60 | |
h -= 1 | |
} | |
if h < 0 { | |
h += 24 | |
} | |
return Clock{h, m} | |
} | |
func (c Clock) Add(minutes int) Clock { | |
return New(c.hours, c.minutes+minutes) | |
} | |
func (c Clock) Subtract(minutes int) Clock { | |
return New(c.hours, c.minutes-minutes) | |
} | |
func (c Clock) String() string { | |
return fmt.Sprintf("%02d:%02d", c.hours, c.minutes) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment