github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/op/api.go (about) 1 // Package op provides generic operations that can be used for converting or reducing collections, loops, slices 2 package op 3 4 import ( 5 "golang.org/x/exp/constraints" 6 7 "github.com/m4gshm/gollections/c" 8 ) 9 10 // Sum returns the sum of two operands 11 func Sum[T c.Summable](a T, b T) T { 12 return a + b 13 } 14 15 // Sub returns the substraction of the b from the a 16 func Sub[T c.Number](a T, b T) T { 17 return a - b 18 } 19 20 // Max returns the maximum from two operands 21 func Max[T constraints.Ordered](a T, b T) T { 22 return IfElse(a < b, b, a) 23 } 24 25 // Min returns the minimum from two operands 26 func Min[T constraints.Ordered](a T, b T) T { 27 return IfElse(a > b, b, a) 28 } 29 30 // IfElse returns the tru value if ok, otherwise return the fal value 31 func IfElse[T any](ok bool, tru, fal T) T { 32 if ok { 33 return tru 34 } 35 return fal 36 } 37 38 // IfElseErr returns the tru value if ok, otherwise return the specified error 39 func IfElseErr[T any](ok bool, tru T, err error) (T, error) { 40 if ok { 41 return tru, nil 42 } 43 var fal T 44 return fal, err 45 } 46 47 // IfGetElse exececutes the tru func if ok, otherwise exec the fal function and returns it result 48 func IfGetElse[T any](ok bool, tru, fal func() T) T { 49 if ok { 50 return tru() 51 } 52 return fal() 53 } 54 55 // IfGetElseGetErr exececutes the tru func if ok, otherwise exec the fal function and returns its error 56 func IfGetElseGetErr[T any](ok bool, tru func() T, fal func() error) (T, error) { 57 if ok { 58 return tru(), nil 59 } 60 var no T 61 return no, fal() 62 } 63 64 // Get calls the getter and returns the result 65 func Get[T any](getter func() T) T { 66 return getter() 67 } 68 69 // Compare returns -1 if o1 less than o2, 0 if equal and 1 if 01 more tha o2 70 func Compare[O constraints.Ordered](o1, o2 O) int { 71 if o1 < o2 { 72 return -1 73 } else if o1 > o2 { 74 return 1 75 } 76 return 0 77 }