tprint/utils.go

60 lines
1009 B
Go
Raw Permalink Normal View History

2022-08-25 16:03:24 +02:00
package tprint
2022-08-25 16:00:13 +02:00
import (
2022-08-25 16:55:19 +02:00
"fmt"
2022-08-25 16:00:13 +02:00
"strings"
"unicode"
)
func maxLengthStr(a, b string) string {
if strLen(a) > strLen(b) {
return a
}
return b
}
func maxLengthSlice[T any](a, b []T) []T {
if len(a) > len(b) {
return a
}
return b
}
func strLen(str string) int {
l := 0
runes := []rune(str)
for i := 0; i < len(runes); i++ {
2022-08-25 16:55:19 +02:00
// skip control sequences
2022-08-25 16:00:13 +02:00
if unicode.IsControl(runes[i]) {
2022-08-25 16:55:19 +02:00
for j := i; j < len(runes)-1 && runes[j] != 'm'; j++ {
i = j
2022-08-25 16:00:13 +02:00
}
2022-08-25 16:55:19 +02:00
i++
2022-08-25 16:00:13 +02:00
continue
}
l++
}
return l
}
func padStringRight(str string, pad rune, length int) string {
padding := length - strLen(str)
return str + strings.Repeat(string(pad), padding)
}
2022-08-25 16:55:19 +02:00
func padStringLeft(str string, pad rune, length int) string {
padding := length - strLen(str)
return strings.Repeat(string(pad), padding) + str
}
func padStringCenter(str string, pad rune, length int) string {
l := strLen(str)
fmt.Println(l, length)
return padStringLeft(padStringRight(str, pad, (length-l)/2+l), pad, length)
}