feat: improve string truncation on proposals names

pull/21/head
Dominique Merle 3 years ago
parent e68f866920
commit 2adc569378

@ -25,28 +25,25 @@ type Formatter interface {
// TruncateString safely truncates a string (hopefully)
// from https://dev.to/takakd/go-safe-truncate-string-9h0
func TruncateString(str string, length int) string {
// with some tweaks, like the suffix ; the length includes the suffix
// Supports Japanese, see Range loops https://blog.golang.org/strings
// Provide a space as rune to disable the suffix
func TruncateString(str string, length int, suffix rune) string {
if length <= 0 {
return ""
}
// This code cannot support Japanese
// orgLen := len(str)
// if orgLen <= length {
// return str
// }
// return str[:length]
// Support Japanese
// Ref: Range loops https://blog.golang.org/strings
truncated := ""
count := 0
for _, char := range str {
truncated += string(char)
count++
if count >= length {
if suffix != ' ' {
truncated = replaceAtIndex(truncated, suffix, length-1)
}
break
}
truncated += string(char)
count++
}
return truncated
}

@ -51,7 +51,7 @@ func (t *GnuplotMeritFormatter) Format(
for _, proposalResult := range proposalsResults {
proposalTally := pollTally.Proposals[proposalResult.Index]
row := make([]string, 0, 10)
row = append(row, TruncateString(proposals[proposalResult.Index], 23))
row = append(row, TruncateString(proposals[proposalResult.Index], 23, '…'))
for gradeIndex := range grades {
row = append(row, strconv.FormatFloat(

@ -33,7 +33,7 @@ func (t *GnuplotOpinionFormatter) Format(
}
}
for i, proposalName := range proposalsNames {
proposalsNames[i] = TruncateString(proposalName, 16)
proposalsNames[i] = TruncateString(proposalName, 16, '…')
}
buffer := new(bytes.Buffer)

@ -62,7 +62,7 @@ func (t *TextFormatter) Format(
line += fmt.Sprintf(
" %*s ",
amountOfCharactersForProposal,
proposals[proposalResult.Index],
TruncateString(proposals[proposalResult.Index], amountOfCharactersForProposal, '…'),
)
remainingWidth := expectedWidth - len(line)

Loading…
Cancel
Save