Skip to content

Commit

Permalink
feat: add u.RandomLetters helper
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Apr 29, 2021
1 parent f34f003 commit f979538
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ func PathExists(path string) bool
func PrettyJSON(input interface{}) string
PrettyJSON returns an indented JSON representation of the passed input.
func RandomLetters(n int) string
RandomLetters returns a string containing 'n' random letters.
func SafeExec(cmd *exec.Cmd) string
SafeExec runs a command and return a string containing the combined standard
output and standard error. If the program fails, the result of `err` is
Expand Down
1 change: 1 addition & 0 deletions depaware.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ moul.io/u dependencies: (generated by github.com/tailscale/depaware)
io/ioutil from moul.io/u
math from compress/flate+
math/bits from compress/flate+
math/rand from moul.io/u
os from archive/zip+
os/exec from moul.io/u
os/signal from moul.io/u
Expand Down
14 changes: 14 additions & 0 deletions rand.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package u

import "math/rand"

const randomLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

// RandomLetters returns a string containing 'n' random letters.
func RandomLetters(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = randomLetters[rand.Intn(len(randomLetters))]
}
return string(b)
}
21 changes: 21 additions & 0 deletions rand_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package u_test

import (
"fmt"
"math/rand"

"moul.io/u"
)

func ExampleRandomLetters() {
rand.Seed(42)
fmt.Println(u.RandomLetters(8))
fmt.Println(u.RandomLetters(8))
fmt.Println(u.RandomLetters(8))
fmt.Println(u.RandomLetters(42))
// Output:
// HRukpTTu
// eZPtNeuv
// unhuksqV
// GzAdxlgghEjkMVeZJpmKqakmTRgKfBSWYjUNGkdmdt
}

0 comments on commit f979538

Please sign in to comment.