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

feat: add Shuffle for string

This commit is contained in:
dudaodong
2024-09-03 15:54:05 +08:00
parent c32a19868d
commit 63216d9b1c
4 changed files with 82 additions and 1 deletions

View File

@@ -5,13 +5,18 @@ package strutil
import (
"errors"
"math/rand"
"regexp"
"strings"
"time"
"unicode"
"unicode/utf8"
"unsafe"
)
// used in `Shuffle` function
var rng = rand.New(rand.NewSource(int64(time.Now().UnixNano())))
// CamelCase coverts string to camelCase string. Non letters and numbers will be ignored.
// Play: https://go.dev/play/p/9eXP3tn2tUy
func CamelCase(s string) string {
@@ -658,3 +663,16 @@ func Ellipsis(str string, length int) string {
return string(runes[:length]) + "..."
}
// Shuffle the order of characters of given string.
// Play: todo
func Shuffle(str string) string {
runes := []rune(str)
for i := len(runes) - 1; i > 0; i-- {
j := rng.Intn(i + 1)
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

View File

@@ -728,3 +728,16 @@ func TestEllipsis(t *testing.T) {
assert.Equal(tt.want, Ellipsis(tt.input, tt.length))
}
}
func TestShuffle(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestShuffle")
assert.Equal("", Shuffle(""))
assert.Equal("a", Shuffle("a"))
str := "hello"
shuffledStr := Shuffle(str)
assert.Equal(5, len(shuffledStr))
}