Skip to content

Commit

Permalink
新增,随机生成指定长度的数字
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Dec 29, 2024
1 parent fc7f214 commit 7e0c8d0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
14 changes: 13 additions & 1 deletion str/pad.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package str

import "strings"
import (
"math/rand"
"strings"
"time"

"github.com/farseer-go/fs/parse"
)

// PadLeft 为str向左填充paddingChar,直到长度=totalWidth
func PadLeft(str string, totalWidth int, paddingChar string) string {
Expand All @@ -17,3 +23,9 @@ func PadRight(str string, totalWidth int, paddingChar string) string {
}
return str + strings.Repeat(paddingChar, totalWidth-Length(str))
}

// RandString 随机字符串
func RandInt64(max int) string {
val := parse.ToString(rand.New(rand.NewSource(time.Now().UnixNano())).Intn(max))
return PadLeft(val, len(parse.ToString(max)), "0")
}
7 changes: 6 additions & 1 deletion test/str_pad_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package test

import (
"testing"

"github.com/farseer-go/utils/str"
"github.com/stretchr/testify/assert"
"testing"
)

func TestPadRight(t *testing.T) {
Expand All @@ -15,3 +16,7 @@ func TestPadLeft(t *testing.T) {
assert.Equal(t, str.PadLeft("1", 5, "0"), "00001")
assert.Equal(t, str.PadLeft("哈哈", 5, "哼"), "哼哼哼哈哈")
}

func TestRandInt64(t *testing.T) {
assert.Equal(t, len(str.RandInt64(999999999)), 9)
}

0 comments on commit 7e0c8d0

Please sign in to comment.