github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/pkg/helper/rand.go (about) 1 package helper 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 8 commonUtils "github.com/easysoft/zendata/pkg/utils/common" 9 ) 10 11 func GetRandFromList(list []string, repeat, count int) (ret []interface{}) { 12 for i := 0; i < count; i++ { 13 rand := commonUtils.RandNum(len(list)) 14 val := list[rand] 15 16 items := make([]string, 0) 17 for round := 0; round < repeat; round++ { 18 items = append(items, val) 19 } 20 21 ret = append(ret, strings.Join(items, "")) 22 } 23 24 return ret 25 } 26 27 func GetRandValuesFromRange(dataType, start, end, step string, repeat int, repeatTag, precisionStr string, 28 format string, count int) (ret []interface{}) { 29 30 precision, _ := strconv.Atoi(precisionStr) 31 32 items := make([]interface{}, 0) 33 34 if dataType == "int" { 35 startInt, _ := strconv.ParseInt(start, 0, 64) 36 endInt, _ := strconv.ParseInt(end, 0, 64) 37 stepInt, _ := strconv.ParseInt(step, 0, 64) 38 39 if endInt < startInt && stepInt > 0 { 40 stepInt = stepInt * -1 41 } 42 43 items = GenerateItems(startInt, endInt, stepInt, 0, true, repeat, repeatTag, count) 44 45 } else if dataType == "char" { 46 startChar := start[0] 47 endChar := end[0] 48 stepInt, _ := strconv.ParseInt(step, 10, 64) 49 50 if int64(endChar) < int64(startChar) && stepInt > 0 { 51 stepInt = stepInt * -1 52 } 53 54 items = GenerateItems(startChar, endChar, stepInt, 0, true, repeat, repeatTag, count) 55 56 } else if dataType == "float" { 57 58 startFloat, _ := strconv.ParseFloat(start, 64) 59 endFloat, _ := strconv.ParseFloat(end, 64) 60 stepFloat, _ := strconv.ParseFloat(step, 64) 61 62 if endFloat < startFloat && stepFloat > 0 { 63 stepFloat = stepFloat * -1 64 } 65 66 items = GenerateItems(startFloat, endFloat, stepFloat, precision, true, repeat, repeatTag, count) 67 68 } 69 70 for _, item := range items { 71 typ := commonUtils.GetType(item) 72 val := item 73 74 if format != "" { // need to format for string 75 val = getFormatStr(item, precision, format) 76 } else if typ == "float" && precision != 0 { 77 val = commonUtils.ChanePrecision(item.(float64), precision) 78 } 79 80 ret = append(ret, val) 81 } 82 83 return 84 } 85 86 func getFormatStr(val interface{}, precision int, format string) (ret string) { 87 typ := GetType(val) 88 89 if format == "" { 90 if typ == "int" { 91 ret = fmt.Sprintf("%d", val) 92 } else if typ == "char" { 93 ret = string(val.(uint8)) 94 } else if typ == "float" { 95 ret = strconv.FormatFloat(val.(float64), 'f', precision, 64) 96 } 97 98 } else { 99 formatVal, success := FormatStr(format, val, 0) 100 if success { 101 ret = formatVal 102 } else { 103 ret = fmt.Sprintf("%d", val) 104 } 105 } 106 107 return 108 }