Improved speller readability

This commit is contained in:
Egor 2024-06-04 17:26:02 +03:00
parent 5bc4119abb
commit 79bb3b15d7

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
var numToDigits = []string{ var digits = []string{
"", "one", "two", "three", "four", "five", "", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "six", "seven", "eight", "nine",
} }
@ -41,48 +41,46 @@ func Spell(n int64) string {
if sign { if sign {
n = -n n = -n
} }
num, digits := strings.Builder{}, digitsReversedSlice(n) num, numDigits := strings.Builder{}, digitsReversedSlice(n)
// 35 is the optimal number which gives approx needed // 35 is the optimal number which gives approx needed
// space for the number in 1 allocation // space for the number in 1 allocation
num.Grow(len(digits) * 35) num.Grow(len(numDigits) * 35)
if sign { if sign {
num.WriteString("minus ") num.WriteString("minus ")
} }
largeIndex, iters := 0, 0 for i, largeIndex := len(numDigits)-1, 0; i >= 0; i, largeIndex = i-3, largeIndex+1 {
for i := len(digits) - 1; i >= 0; i, largeIndex = i-3, largeIndex+1 { hundreds, tens, ones := numDigits[i], numDigits[i-1], numDigits[i-2]
first, second, third := digits[i-2], digits[i-1], digits[i] hundredsPresent, tensPesent, onesPresent := hundreds != 0, tens != 0, ones != 0
if first == 0 && second == 0 && third == 0 { if !hundredsPresent && !tensPesent && !onesPresent {
continue continue
} }
if iters != 0 { if hundredsPresent {
num.WriteRune(' ') num.WriteString(digits[hundreds])
}
hundreds := numToDigits[third]
if hundreds != "" {
num.WriteString(hundreds)
num.WriteString(" hundred") num.WriteString(" hundred")
if second != 0 || first != 0 { if tensPesent || onesPresent {
num.WriteRune(' ') num.WriteRune(' ')
} }
} }
if second > 1 { if tensPesent {
num.WriteString(decs[second]) if tens == 1 {
if first > 0 { num.WriteString(teens[ones])
num.WriteRune('-') } else {
num.WriteString(numToDigits[first]) num.WriteString(decs[tens])
} if onesPresent {
} else if second == 1 { num.WriteRune('-')
num.WriteString(teens[first]) }
} else {
if first > 0 {
num.WriteString(numToDigits[first])
} }
} }
if onesPresent && tens != 1 {
num.WriteString(digits[ones])
}
if largeIndex < len(large) { if largeIndex < len(large) {
num.WriteRune(' ') num.WriteRune(' ')
num.WriteString(large[largeIndex]) num.WriteString(large[largeIndex])
} }
iters++ num.WriteRune(' ')
} }
return num.String() output := num.String()
output = output[:len(output)-1]
return output
} }