Skip to content

Commit

Permalink
Refactor: move RandString functions to rand.go (#44)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiendc authored Jul 10, 2024
1 parent fa686be commit b0c5443
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 103 deletions.
98 changes: 49 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -481,11 +481,11 @@ Joins a slice of any element type.
s := StringJoin([]int{1,2,3}, ", ") // s == "1, 2, 3"

type Struct struct {
I int
S string
I int
S string
}
s := StringJoinPred([]Struct{{I:1, s:"a"}, {I:2, s:"b"}}, ", ", func (v Struct) string {
return fmt.Sprintf("%d:%s", v.I, v.S)
return fmt.Sprintf("%d:%s", v.I, v.S)
}) // s == "1:a, 2:b"
```

Expand All @@ -495,16 +495,16 @@ Removes all leading spaces from every line in the given string. This function is

```go
func DoSomething() {
// Commonly you may use this style to create multiline string in Go (which looks ugly)
s := `
// Commonly you may use this style to create multiline string in Go (which looks ugly)
s := `
line-1 abc xyz
line-2 abc xyz
`
// Use this function
s := MultilineString(
`line-1 abc xyz
line-2 abc xyz`
)
// Use this function
s := MultilineString(
`line-1 abc xyz
line-2 abc xyz`
)
}
```

Expand Down Expand Up @@ -814,6 +814,41 @@ ForEachReverse([]int{1, 2, 3}, func (i, v int) {
}) // prints 3 2 1
```

#### All

Returns `true` if all given values are evaluated `true`.

```go
All(1, "1", 0.5) // true
All(1, "1", 0.0) // false
All(1, "", -1) // false
All() // true
```

#### Any

Returns `true` if any of the given values is evaluated `true`.

```go
Any(1, "", 0.5) // true
Any(1, "1", 0.0) // true
Any(0, "", 0.0) // false
Any() // false
```

#### MustN (N is from 1 to 6)

MustN functions accept a number of arguments with the last one is of `error` type.
MustN functions return the first N-1 arguments if the error is `nil`, otherwise they panic.

```go
func CalculateAmount() (int, error) {}
amount := Must(CalculateAmount()) // panic on error, otherwise returns the amount

func CalculateData() (int, string, float64, error) {}
v1, v2, v3 := Must4(CalculateData()) // panic on error, otherwise returns the 3 first values
```

### Randomization functions

**NOTE**: Should not use these functions for crypto purpose.
Expand Down Expand Up @@ -855,39 +890,13 @@ Shuffle items of a slice. Not change the source slice.
s := Shuffle([]int{1, 2, 3}) // s is a new slice with random items of the input
```

#### All

Returns `true` if all given values are evaluated `true`.

```go
All(1, "1", 0.5) // true
All(1, "1", 0.0) // false
All(1, "", -1) // false
All() // true
```

#### Any

Returns `true` if any of the given values is evaluated `true`.

```go
Any(1, "", 0.5) // true
Any(1, "1", 0.0) // true
Any(0, "", 0.0) // false
Any() // false
```

#### MustN (N is from 1 to 6)
#### RandString

MustN functions accept a number of arguments with the last one is of `error` type.
MustN functions return the first N-1 arguments if the error is `nil`, otherwise they panic.
Generates a random string.

```go
func CalculateAmount() (int, error) {}
amount := Must(CalculateAmount()) // panic on error, otherwise returns the amount

func CalculateData() (int, string, float64, error) {}
v1, v2, v3 := Must4(CalculateData()) // panic on error, otherwise returns the 3 first values
RandString(10) // a random string has 10 characters (default of alphabets and digits)
RandStringEx(10, []rune("01234")) // a random string has 10 characters (only 0-4)
```

### Sorting functions
Expand Down Expand Up @@ -994,15 +1003,6 @@ Abs(123) // int64(123)
Abs(math.MinInt64) // math.MinInt64 (special case)
```

#### RandString

Generates a random string.

```go
RandString(10) // a random string has 10 characters (default of alphabets and digits)
RandStringEx(10, []rune("01234")) // a random string has 10 characters (only 0-4)
```

### Other functions

---
Expand Down
22 changes: 22 additions & 0 deletions rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@ package gofn

import "math/rand"

var (
StrLowerAlpha = []rune("abcdefghijklmnopqrstuvwxyz")
StrUpperAlpha = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
StrDigits = []rune("0123456789")
StrDefaultChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
)

// RandChoiceMaker a struct for picking up items randomly from a list of items
type RandChoiceMaker[T any] struct {
source []*T // Use pointers to slice items to gain more performance when item type is struct
Expand Down Expand Up @@ -73,3 +80,18 @@ func Shuffle[T any](s []T, randFuncs ...func(n int) int) []T {
}
return result
}

// RandString generates a random string
func RandString(n int) string {
return RandStringEx(n, StrDefaultChars)
}

// RandStringEx generates a random string
func RandStringEx(n int, allowedChars []rune) string {
b := make([]rune, n)
numChars := len(allowedChars)
for i := range b {
b[i] = allowedChars[rand.Intn(numChars)] // nolint: gosec
}
return string(b)
}
31 changes: 31 additions & 0 deletions rand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gofn

import (
"math/rand"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -66,3 +67,33 @@ func Test_Shuffle(t *testing.T) {
Sort(s3)
assert.Equal(t, []string{"1", "2", "3"}, s3)
}

func Test_RandString(t *testing.T) {
// Empty string
assert.Equal(t, "", RandString(0))

s := RandString(12)
assert.Equal(t, 12, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrDefaultChars), ch))
}
}

func Test_RandStringEx(t *testing.T) {
// Empty string
assert.Equal(t, "", RandStringEx(0, StrLowerAlpha))

// Only digits
s := RandStringEx(10, StrDigits)
assert.Equal(t, 10, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrDigits), ch))
}

// Only alphabet
s = RandStringEx(12, StrLowerAlpha)
assert.Equal(t, 12, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrLowerAlpha), ch))
}
}
23 changes: 0 additions & 23 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,9 @@ package gofn

import (
"fmt"
"math/rand"
"strings"
)

var (
StrLowerAlpha = []rune("abcdefghijklmnopqrstuvwxyz")
StrUpperAlpha = []rune("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
StrDigits = []rune("0123456789")
StrDefaultChars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
)

// RandString generates a random string
func RandString(n int) string {
return RandStringEx(n, StrDefaultChars)
}

// RandStringEx generates a random string
func RandStringEx(n int, allowedChars []rune) string {
b := make([]rune, n)
numChars := len(allowedChars)
for i := range b {
b[i] = allowedChars[rand.Intn(numChars)] // nolint: gosec
}
return string(b)
}

// StringJoin join elements from a slice of any type
// This function calls fmt.Sprintf("%v", elem) to format every element
func StringJoin[T any](s []T, sep string) string {
Expand Down
31 changes: 0 additions & 31 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,12 @@ package gofn

import (
"fmt"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func Test_RandString(t *testing.T) {
// Empty string
assert.Equal(t, "", RandString(0))

s := RandString(12)
assert.Equal(t, 12, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrDefaultChars), ch))
}
}

func Test_RandStringEx(t *testing.T) {
// Empty string
assert.Equal(t, "", RandStringEx(0, StrLowerAlpha))

// Only digits
s := RandStringEx(10, StrDigits)
assert.Equal(t, 10, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrDigits), ch))
}

// Only alphabet
s = RandStringEx(12, StrLowerAlpha)
assert.Equal(t, 12, len(s))
for _, ch := range s {
assert.True(t, strings.ContainsRune(string(StrLowerAlpha), ch))
}
}

func Test_StringJoin(t *testing.T) {
assert.Equal(t, "", StringJoin[int](nil, ","))
assert.Equal(t, "1", StringJoin[int]([]int{1}, ","))
Expand Down

0 comments on commit b0c5443

Please sign in to comment.