govote/voting/vote/choice.go

47 lines
933 B
Go
Raw Permalink Normal View History

2024-05-12 22:47:24 +00:00
package vote
import (
"fmt"
"strings"
)
2024-05-14 08:26:48 +00:00
// Choice defines a custom int8 type for use as choice in a vote.
2024-05-12 22:47:24 +00:00
type Choice int8
2024-05-14 08:26:48 +00:00
// String implements fmt.Stringer
2024-05-12 22:47:24 +00:00
func (choice Choice) String() string {
2024-05-13 08:45:38 +00:00
switch choice {
case Yes:
return "YIP"
case No:
return "NOPE"
case Abstain:
return "DUNNO"
default:
panic("this code should never be reached")
}
2024-05-12 22:47:24 +00:00
}
2024-05-14 08:26:48 +00:00
// Available choices are:
2024-05-12 22:47:24 +00:00
const (
2024-05-13 08:45:38 +00:00
Abstain Choice = 0
Yes Choice = 1
No Choice = -1
2024-05-12 22:47:24 +00:00
)
2024-05-14 08:26:48 +00:00
// ValidChoices returns a []Choice with all available choices.
2024-05-12 22:47:24 +00:00
func ValidChoices() []Choice {
2024-05-13 08:45:38 +00:00
return []Choice{Yes, No, Abstain}
2024-05-12 22:47:24 +00:00
}
2024-05-14 08:26:48 +00:00
// ChoiceFromString takes a string and returns an initialized Choice or an
// error if the string couldn't be parsed.
2024-05-12 22:47:24 +00:00
func ChoiceFromString(s string) (Choice, error) {
2024-05-13 08:45:38 +00:00
for _, c := range ValidChoices() {
if strings.ToUpper(c.String()) == strings.ToUpper(s) {
return c, nil
}
}
return Abstain, fmt.Errorf("invalid choice: %s", s)
2024-05-12 22:47:24 +00:00
}