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