You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
majority-judgment-cli/formatter/csv.go

65 lines
1.3 KiB

package formatter
import (
"bytes"
"encoding/csv"
"github.com/mieuxvoter/majority-judgment-library-go/judgment"
"log"
"strconv"
)
// CsvFormatter formats the results as CSV, with , as delimiter and " as quote
type CsvFormatter struct{}
// Format the provided results
func (t *CsvFormatter) Format(
pollTally *judgment.PollTally,
result *judgment.PollResult,
proposals []string,
grades []string,
options *Options,
) (string, error) {
proposalsResults := result.Proposals
if options.Sorted {
proposalsResults = result.ProposalsSorted
}
buffer := new(bytes.Buffer)
writer := csv.NewWriter(buffer)
if err := writer.Error(); err != nil {
log.Fatal(err)
}
headersWriteErr := writer.Write([]string{
"Rank",
"Proposal",
"Score",
"MajorityGrade",
"SecondMajorityGrade",
})
if nil != headersWriteErr {
log.Fatal(headersWriteErr)
}
for _, proposalResult := range proposalsResults {
writeErr := writer.Write([]string{
strconv.Itoa(proposalResult.Rank),
proposals[proposalResult.Index],
proposalResult.Score,
grades[proposalResult.Analysis.MedianGrade],
grades[proposalResult.Analysis.SecondMedianGrade],
})
if nil != writeErr {
log.Fatal(writeErr)
}
}
writer.Flush() // I've also seen "defer" prefixed here. Gotta RTFM
return buffer.String(), nil
}