Compare commits

...

6 Commits

9 changed files with 212 additions and 54 deletions

View File

@@ -3,6 +3,6 @@ BFB goext library
A collection of general & useful library methods
Every subfolder is a seperate dependency and can be imported individually
This should not have any heavy dependencies (gin, mongo, etc) and add missing basic language features...
Potentially needs `export GOPRIVATE="gogs.mikescher.com"`

View File

@@ -4,6 +4,24 @@ import (
"reflect"
)
func BoolCount(arr ...bool) int {
c := 0
for _, v := range arr {
if v {
c++
}
}
return c
}
func Range[T IntegerConstraint](start T, end T) []T {
r := make([]T, 0, end-start)
for i := start; i < end; i++ {
r = append(r, i)
}
return r
}
func ForceArray[T any](v []T) []T {
if v == nil {
return make([]T, 0)
@@ -124,6 +142,27 @@ func ArrAnyErr(arr interface{}, fn func(int) (bool, error)) (bool, error) {
return false, nil
}
func ArrFirst[T comparable](arr []T, comp func(v T) bool) (T, bool) {
for _, v := range arr {
if comp(v) {
return v, true
}
}
return *new(T), false
}
func ArrLast[T comparable](arr []T, comp func(v T) bool) (T, bool) {
found := false
result := *new(T)
for _, v := range arr {
if comp(v) {
found = true
result = v
}
}
return result, found
}
func AddToSet[T comparable](set []T, add T) []T {
for _, v := range set {
if v == add {

74
langext/base62.go Normal file
View File

@@ -0,0 +1,74 @@
package langext
import (
"crypto/rand"
"errors"
"math"
"math/big"
"strings"
)
var (
base62Base = uint64(62)
base62CharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
func RandBase62(rlen int) string {
bi52 := big.NewInt(int64(len(base62CharacterSet)))
randMax := big.NewInt(math.MaxInt64)
r := ""
for i := 0; i < rlen; i++ {
v, err := rand.Int(rand.Reader, randMax)
if err != nil {
panic(err)
}
r += string(base62CharacterSet[v.Mod(v, bi52).Int64()])
}
return r
}
func EncodeBase62(num uint64) string {
if num == 0 {
return "0"
}
b := make([]byte, 0)
// loop as long the num is bigger than zero
for num > 0 {
r := num % base62Base
num -= r
num /= base62Base
b = append([]byte{base62CharacterSet[int(r)]}, b...)
}
return string(b)
}
func DecodeBase62(str string) (uint64, error) {
if str == "" {
return 0, errors.New("empty string")
}
result := uint64(0)
for _, v := range str {
result *= base62Base
pos := strings.IndexRune(base62CharacterSet, v)
if pos == -1 {
return 0, errors.New("invalid character: " + string(v))
}
result += uint64(pos)
}
return result, nil
}

View File

@@ -3,3 +3,31 @@ package langext
type IntConstraint interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}
type SignedConstraint interface {
~int | ~int8 | ~int16 | ~int32 | ~int64
}
type UnsignedConstraint interface {
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
type IntegerConstraint interface {
SignedConstraint | UnsignedConstraint
}
type FloatConstraint interface {
~float32 | ~float64
}
type ComplexConstraint interface {
~complex64 | ~complex128
}
type OrderedConstraint interface {
IntegerConstraint | FloatConstraint | ~string
}
type NumberConstraint interface {
IntegerConstraint | FloatConstraint
}

View File

@@ -3,8 +3,6 @@ package langext
import (
"crypto/rand"
"io"
"math"
"math/big"
)
func RandBytes(size int) []byte {
@@ -15,24 +13,3 @@ func RandBytes(size int) []byte {
}
return b
}
func RandBase62(rlen int) string {
ecs := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
bi52 := big.NewInt(int64(len(ecs)))
randMax := big.NewInt(math.MaxInt64)
r := ""
for i := 0; i < rlen; i++ {
v, err := rand.Int(rand.Reader, randMax)
if err != nil {
panic(err)
}
r += string(ecs[v.Mod(v, bi52).Int64()])
}
return r
}

View File

@@ -1,5 +1,7 @@
package mathext
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func AvgFloat64(arr []float64) float64 {
return SumFloat64(arr) / float64(len(arr))
}
@@ -11,3 +13,19 @@ func SumFloat64(arr []float64) float64 {
}
return sum
}
func Max[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 > v2 {
return v1
} else {
return v2
}
}
func Min[T langext.OrderedConstraint](v1 T, v2 T) T {
if v1 < v2 {
return v1
} else {
return v2
}
}

View File

@@ -1,26 +1,28 @@
package mathext
func Sum(v []float64) float64 {
total := float64(0)
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func Sum[T langext.NumberConstraint](v []T) T {
total := T(0)
for _, v := range v {
total += v
}
return total
}
func Mean(v []float64) float64 {
return Sum(v) / float64(len(v))
func Mean[T langext.FloatConstraint](v []T) T {
return Sum(v) / T(len(v))
}
func Median(v []float64) float64 {
func Median[T langext.FloatConstraint](v []T) T {
if len(v)%2 == 1 {
return v[len(v)/2]
} else {
return (v[len(v)/2-1] + v[len(v)/2]) / float64(2)
return (v[len(v)/2-1] + v[len(v)/2]) / T(2)
}
}
func Min(v []float64) float64 {
func ArrMin[T langext.OrderedConstraint](v []T) T {
r := v[0]
for _, val := range v {
if val < r {
@@ -30,7 +32,7 @@ func Min(v []float64) float64 {
return r
}
func Max(v []float64) float64 {
func ArrMax[T langext.OrderedConstraint](v []T) T {
r := v[0]
for _, val := range v {
if val > r {

View File

@@ -1,5 +1,7 @@
package termext
import "strings"
const (
colorReset = "\033[0m"
colorRed = "\033[31m"
@@ -43,3 +45,17 @@ func Gray(v string) string {
func White(v string) string {
return colorWhite + v + colorReset
}
func CleanString(v string) string {
v = strings.ReplaceAll(v, colorReset, "")
v = strings.ReplaceAll(v, colorRed, "")
v = strings.ReplaceAll(v, colorGreen, "")
v = strings.ReplaceAll(v, colorYellow, "")
v = strings.ReplaceAll(v, colorBlue, "")
v = strings.ReplaceAll(v, colorPurple, "")
v = strings.ReplaceAll(v, colorCyan, "")
v = strings.ReplaceAll(v, colorGray, "")
v = strings.ReplaceAll(v, colorWhite, "")
return v
}

View File

@@ -17,14 +17,14 @@ func init() {
}
// TimeToDatePart returns a timestamp at the start of the day which contains t (= 00:00:00)
func TimeToDatePart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToDatePart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
// TimeToWeekStart returns a timestamp at the start of the week which contains t (= Monday 00:00:00)
func TimeToWeekStart(t time.Time) time.Time {
t = TimeToDatePart(t)
func TimeToWeekStart(t time.Time, tz *time.Location) time.Time {
t = TimeToDatePart(t, tz)
delta := time.Duration(((int64(t.Weekday()) + 6) % 7) * 24 * int64(time.Hour))
t = t.Add(-1 * delta)
@@ -33,32 +33,32 @@ func TimeToWeekStart(t time.Time) time.Time {
}
// TimeToMonthStart returns a timestamp at the start of the month which contains t (= yyyy-MM-00 00:00:00)
func TimeToMonthStart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToMonthStart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}
// TimeToMonthEnd returns a timestamp at the end of the month which contains t (= yyyy-MM-31 23:59:59.999999999)
func TimeToMonthEnd(t time.Time) time.Time {
return TimeToMonthStart(t).AddDate(0, 1, 0).Add(-1)
func TimeToMonthEnd(t time.Time, tz *time.Location) time.Time {
return TimeToMonthStart(t, tz).AddDate(0, 1, 0).Add(-1)
}
// TimeToYearStart returns a timestamp at the start of the year which contains t (= yyyy-01-01 00:00:00)
func TimeToYearStart(t time.Time) time.Time {
t = t.In(TimezoneBerlin)
func TimeToYearStart(t time.Time, tz *time.Location) time.Time {
t = t.In(tz)
return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
}
// TimeToYearEnd returns a timestamp at the end of the month which contains t (= yyyy-12-31 23:59:59.999999999)
func TimeToYearEnd(t time.Time) time.Time {
return TimeToYearStart(t).AddDate(1, 0, 0).Add(-1)
func TimeToYearEnd(t time.Time, tz *time.Location) time.Time {
return TimeToYearStart(t, tz).AddDate(1, 0, 0).Add(-1)
}
// IsSameDayIncludingDateBoundaries returns true if t1 and t2 are part of the same day (TZ/Berlin), the boundaries of the day are
// inclusive, this means 2021-09-15T00:00:00 is still part of the day 2021-09-14
func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool {
dp1 := TimeToDatePart(t1)
dp2 := TimeToDatePart(t2)
func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time, tz *time.Location) bool {
dp1 := TimeToDatePart(t1, tz)
dp2 := TimeToDatePart(t2, tz)
if dp1.Equal(dp2) {
return true
@@ -72,9 +72,9 @@ func IsSameDayIncludingDateBoundaries(t1 time.Time, t2 time.Time) bool {
}
// IsDatePartEqual returns true if a and b have the same date part (`yyyy`, `MM` and `dd`)
func IsDatePartEqual(a time.Time, b time.Time) bool {
yy1, mm1, dd1 := a.In(TimezoneBerlin).Date()
yy2, mm2, dd2 := b.In(TimezoneBerlin).Date()
func IsDatePartEqual(a time.Time, b time.Time, tz *time.Location) bool {
yy1, mm1, dd1 := a.In(tz).Date()
yy2, mm2, dd2 := b.In(tz).Date()
return yy1 == yy2 && mm1 == mm2 && dd1 == dd2
}
@@ -82,7 +82,7 @@ func IsDatePartEqual(a time.Time, b time.Time) bool {
// WithTimePart returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from base
// and the time (`HH`, `mm`, `ss`) from the parameter
func WithTimePart(base time.Time, hour, minute, second int) time.Time {
datepart := TimeToDatePart(base)
datepart := TimeToDatePart(base, base.Location())
delta := time.Duration(hour*int(time.Hour) + minute*int(time.Minute) + second*int(time.Second))
@@ -92,7 +92,7 @@ func WithTimePart(base time.Time, hour, minute, second int) time.Time {
// CombineDateAndTime returns a timestamp with the date-part (`yyyy`, `MM`, `dd`) from the d parameter
// and the time (`HH`, `mm`, `ss`) from the t parameter
func CombineDateAndTime(d time.Time, t time.Time) time.Time {
datepart := TimeToDatePart(d)
datepart := TimeToDatePart(d, d.Location())
delta := time.Duration(t.Hour()*int(time.Hour) + t.Minute()*int(time.Minute) + t.Second()*int(time.Second) + t.Nanosecond()*int(time.Nanosecond))
@@ -100,8 +100,8 @@ func CombineDateAndTime(d time.Time, t time.Time) time.Time {
}
// IsSunday returns true if t is a sunday (in TZ/Berlin)
func IsSunday(t time.Time) bool {
if t.In(TimezoneBerlin).Weekday() == time.Sunday {
func IsSunday(t time.Time, tz *time.Location) bool {
if t.In(tz).Weekday() == time.Sunday {
return true
}
return false
@@ -131,3 +131,7 @@ func UnixFloatSeconds(v float64) time.Time {
sec, dec := math.Modf(v)
return time.Unix(int64(sec), int64(dec*(1e9)))
}
func FloorTime(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}