github.com/qioalice/ekago/v3@v3.3.2-0.20221202205325-5c262d586ee4/ekarand/ekahaiku/haiku.go (about)

     1  // Copyright © 2020-2021. All rights reserved.
     2  // Author: Ilya Stroy.
     3  // Contacts: iyuryevich@pm.me, https://github.com/qioalice
     4  // License: https://opensource.org/licenses/MIT
     5  
     6  package ekahaiku
     7  
     8  // Ruby original: https://github.com/usmanbashir/haikunator
     9  // Go ver of Ruby original: https://github.com/yelinaung/go-haikunator
    10  
    11  import (
    12  	mrand "math/rand"
    13  
    14  	"bytes"
    15  	"strconv"
    16  
    17  	"github.com/qioalice/ekago/v3/ekastr"
    18  )
    19  
    20  // Thanks to https://gist.github.com/hugsy/8910dc78d208e40de42deb29e62df913
    21  // for english adjectives and nouns.
    22  
    23  // Haikunate returns a randomized string with the following format:
    24  // `<english_adjective>-<english_noun>-<4_digit>`.
    25  func Haikunate() string {
    26  	return HaikunateWithRange(0, 9999)
    27  }
    28  
    29  // HaikunateWithRange does the same as Haikunate() does but the last number
    30  // is depends of `from`, `to` args and will be in their range.
    31  func HaikunateWithRange(from, to uint) string {
    32  
    33  	if from > to {
    34  		from, to = to, from
    35  	}
    36  
    37  	var (
    38  		n   = ekastr.PItoa64(int64(to)) // bytes required for max number
    39  		rn  = mrand.Uint64() % uint64(to-from)
    40  		rnn = ekastr.PItoa64(int64(rn)) // bytes required for generated number
    41  		b   bytes.Buffer
    42  	)
    43  
    44  	b.Grow(n + 32)
    45  	b.WriteString(adjectives[mrand.Int31n(int32(len(adjectives)))])
    46  	b.WriteByte('-')
    47  	b.WriteString(nouns[mrand.Int31n(int32(len(nouns)))])
    48  	b.WriteByte('-')
    49  
    50  	for i, n := 0, n-rnn; i < n; i++ {
    51  		b.WriteByte('0')
    52  	}
    53  
    54  	return ekastr.B2S(strconv.AppendUint(b.Bytes(), rn, 10))
    55  }