1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

fix: fix bugs of PadEnd and PadStart

This commit is contained in:
dudaodong
2023-02-19 12:34:39 +08:00
parent a774c060ce
commit 84cd68de7f
3 changed files with 45 additions and 33 deletions

View File

@@ -67,44 +67,18 @@ func LowerFirst(s string) string {
return string(r) + s[size:]
}
// PadEnd pads string on the right side if it's shorter than size.
// Padding characters are truncated if they exceed size.
// Play: https://go.dev/play/p/9xP8rN0vz--
func PadEnd(source string, size int, padStr string) string {
len1 := len(source)
len2 := len(padStr)
if len1 >= size {
return source
}
fill := ""
if len2 >= size-len1 {
fill = padStr[0 : size-len1]
} else {
fill = strings.Repeat(padStr, size-len1)
}
return source + fill[0:size-len1]
}
// PadStart pads string on the left side if it's shorter than size.
// Padding characters are truncated if they exceed size.
// Play: https://go.dev/play/p/xpTfzArDfvT
func PadStart(source string, size int, padStr string) string {
len1 := len(source)
len2 := len(padStr)
return padAtPosition(source, size, padStr, 1)
}
if len1 >= size {
return source
}
fill := ""
if len2 >= size-len1 {
fill = padStr[0 : size-len1]
} else {
fill = strings.Repeat(padStr, size-len1)
}
return fill[0:size-len1] + source
// PadEnd pads string on the right side if it's shorter than size.
// Padding characters are truncated if they exceed size.
// Play: https://go.dev/play/p/9xP8rN0vz--
func PadEnd(source string, size int, padStr string) string {
return padAtPosition(source, size, padStr, 2)
}
// KebabCase coverts string to kebab-case, non letters and numbers will be ignored.

View File

@@ -98,3 +98,40 @@ func toUpperAll(rs []rune) []rune {
}
return rs
}
// padWithPosition pads string
func padAtPosition(str string, length int, padStr string, position int) string {
if len(str) >= length {
return str
}
if padStr == "" {
padStr = " "
}
length = length - len(str)
startPadLen := 0
if position == 0 {
startPadLen = length / 2
} else if position == 1 {
startPadLen = length
}
endPadLen := length - startPadLen
charLen := len(padStr)
leftPad := ""
cur := 0
for cur < startPadLen {
leftPad += string(padStr[cur%charLen])
cur++
}
cur = 0
rightPad := ""
for cur < endPadLen {
rightPad += string(padStr[cur%charLen])
cur++
}
return leftPad + str + rightPad
}

View File

@@ -171,6 +171,7 @@ func TestLowerFirst(t *testing.T) {
func TestPadEnd(t *testing.T) {
assert := internal.NewAssert(t, "TestPadEnd")
assert.Equal("a ", PadEnd("a", 2, " "))
assert.Equal("a", PadEnd("a", 1, "b"))
assert.Equal("ab", PadEnd("a", 2, "b"))
assert.Equal("abcdmn", PadEnd("abcd", 6, "mno"))