Add helper functions for rendering polls

This commit is contained in:
Alessio 2023-08-18 14:52:54 -03:00
parent 0c533c632b
commit 57b72549c5
2 changed files with 44 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import (
"net/url"
"strconv"
"strings"
"time"
)
type PollID int64
@ -28,6 +29,26 @@ type Poll struct {
LastUpdatedAt Timestamp `db:"last_scraped_at"`
}
func (p Poll) TotalVotes() int {
return p.Choice1_Votes + p.Choice2_Votes + p.Choice3_Votes + p.Choice4_Votes
}
func (p Poll) VotePercentage(n int) float64 {
return 100.0 * float64(n) / float64(p.TotalVotes())
}
func (p Poll) IsOpen() bool {
return time.Now().Unix() < p.VotingEndsAt.Unix()
}
func (p Poll) FormatEndsAt() string {
return p.VotingEndsAt.Format("Jan 2, 2006 3:04 pm")
}
func (p Poll) IsWinner(votes int) bool {
if p.IsOpen() {
// There's no winner if the poll is still open
return false
}
return votes >= p.Choice1_Votes && votes >= p.Choice2_Votes && votes >= p.Choice3_Votes && votes >= p.Choice4_Votes
}
func ParseAPIPoll(apiCard APICard) Poll {
card_url, err := url.Parse(apiCard.ShortenedUrl)
if err != nil {

View File

@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -65,3 +66,25 @@ func TestParsePoll4Choices(t *testing.T) {
assert.Equal("Derek Chauvin", poll.Choice4)
assert.Equal(2397, poll.Choice4_Votes)
}
func TestPollHelpers(t *testing.T) {
assert := assert.New(t)
p := Poll{
Choice1_Votes: 1,
Choice2_Votes: 2,
Choice3_Votes: 3,
Choice4_Votes: 4,
VotingEndsAt: Timestamp{Time: time.Now().Add(10 * time.Second)},
}
assert.Equal(p.TotalVotes(), 10)
assert.Equal(p.VotePercentage(p.Choice3_Votes), 30.0)
assert.True(p.IsOpen())
assert.False(p.IsWinner(p.Choice4_Votes))
// End the poll
p.VotingEndsAt = Timestamp{Time: time.Now().Add(-10 * time.Second)}
assert.False(p.IsOpen())
assert.False(p.IsWinner(p.Choice2_Votes))
assert.True(p.IsWinner(p.Choice4_Votes))
}