aboutsummaryrefslogtreecommitdiff
path: root/go-src/utils/utils.go
blob: 271dd3e5b440418777ece7e7ce19f44719dc9c26 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package utils

import (
	"math"
	"os"
	"strings"
)

// Repeats a rune given amount of times and returns the result as a string
func RepeatRune(r rune, times int) (result string) {
	for i := 0; i < times; i++ {
		result += string(r)
	}
	return
}

// Replaces a character inside a string with a given rune at index
//
// Thanks https://stackoverflow.com/a/24894202/12036073
func ReplaceAtIndex(in string, r rune, i int) string {
	out := []rune(in)
	out[i] = r
	return string(out)
}

func TwoDByteArrayToStringArray(in [][]byte) (result []string) {
	for _, v := range in {
		result = append(result, string(v))
	}
	return
}

func AppendToFile(path string, value string) {
	allChatsFile, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
	allChatsFile.WriteString(value)
	allChatsFile.Close()
}

func CreateDir(path string) {
	os.Mkdir(path, 0775)
}

func CreateFile(path string) {
	f, _ := os.Create(path)
	f.Close()
}

func PathExists(path string) bool {
	_, err := os.Stat(path)
	return !os.IsNotExist(err)
}

func StrShortenRight(s *string, amount int) {
	*s = (*s)[:len(*s)-amount]
}

func StrMSplit(s string, seps ...string) (sret []string) {
	for _, sep := range seps {
		if len(sret) == 0 {
			sret = strings.Split(s, sep)
		} else {
			var tmp []string
			for _, sepStr := range sret {
				tmp = append(tmp, strings.Split(sepStr, sep)...)
			}
			sret = tmp
		}
	}
	return
}

func MaxInt(x int, y int) int {
	if x > y {
		return x
	}
	return y
}

func CeilDivInt(x int, y int) int {
	return int(math.Ceil(float64(x) / float64(y)))
}

// Special thanks to icza, over on https://stackoverflow.com/a/59375088 for the If constuction

type If bool

func (c If) Int(a, b int) int {
	if c {
		return a
	}
	return b
}

func (c If) String(a, b string) string {
	if c {
		return a
	}
	return b
}