gofuncs

package module
v1.12.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 2, 2021 License: Apache-2.0 Imports: 4 Imported by: 1

README

// SPDX-License-Identifier: Apache-2.0
:doctype: article

= gofuncs

A set of common functions that can be used on multiple projects.

== Function adapters

These functions use type assertion and reflection to accept an empty interface argument and return a specific function signature.
Each adapter first tries to type assert that the argument is the exact function signature desired, and if so, returns the argument as is.
Otherwise, the adapter uses reflection to verify the argument is the correct kind of function and adapt it.
Adapters panic if the function argument does not match expectations. 

* IndexOf(array or slice, index, optional default) safely looks up an index into an array or slice, returning the zero value or default value if there are not enough elements for the index
* ValueOfKey(map, key, optional default) looks up a key in a map, returning the zero value or default given if the key does not exist
* Filter(func) adapts a func(any) bool into a func(interface{}) bool
* FilterAll adapts a vararg of func(any) bool into a []func(interface{}) bool
* And and Or use FilterAll to create conjunction and disjunctions as a func(interface{}) bool
* Not adapts a func(any) bool into a negation func(interface{}) bool
* EqualTo accepts a value and returns a func(interface{}) bool that returns true if the func arg is equal to the value using ==
* DeepEqualTo accepts a value and returns a func(interface{}) bool that returns true if the func arg is equal to the value using reflect.DeepEqual
* IsLessableKind returns true if the given reflect.Kind is any type that compared using the < operator
* LessThan accepts a value and returns a func(val1, val2 interface{}) bool that returns true if val1 < val2
* IsLessThan accepts a value and returns a func(interface{}} bool that returns true if the func arg < the value
* LessThanEquals accepts a value and returns a func(val1, val2 interface{}) bool that returns true if val1 <= val2
* IsLessThanEquals accepts a value and returns a func(val1, val2 interface{}) bool that returns true if val1 <= val2
* GreaterThan accepts a value and returns a func(val1, val2 interface{}) bool that returns true if val1 > val2
* IsGreaterThan accepts a value and returns a func(interface{}) bool that returns true if the func arg > the value
* GreaterThanEquals accepts a value and returns a func(val1, val2 interface{}) bool that returns true if val1 >= val2
* IsGreaterThanEquals accepts a value and returns a func(interface{}) bool that returns true if the func arg >= the value
* IsNegative accepts a value and returns true if it is negative
* IsNonNegative accepts a value and returns true if it is non-negative
* IsPositive accepts a value and returns true if it is positive
* IsNil is a func(interface{}) bool that returns true if the arg is nil
* IsNilable is a func(interface{}) bool that returns true if the type of the value given is a nilable type 
* Map(func) adapts a func(any) any into a func(interface{}) interface{}
* MapTo(func, X) adapts a func(any) X' into a func(interface{}) X where X' is convertible to X
* ConvertTo(val) returns a func(interface{}) interface{} that converts the argument to the type of the value passed
* Supplier(func) adapts a func() any into a func() interface{}
* SupplierOf(func, X) adapts a func() X' into a func() X where X' is convertible to X.
* Consumer(func) adapts a func(any) into a func(interface{})
* Ternary(bool, trueVal, falseVal) returns trueVal is the bool is true, else falseVal
* PanicE(error) panics if the error is non-nil with the wrapped message
* PanicVE(val, error) panics if the error is non-nil with the wrapped message, else returns val
* PanicBM(bool, msg) panics if the bool is false with msg
* PanicVBM(val, bool, msg) panics if the bool is false with msg, else returns val
* SortFunc(func(val21, val2) bool) adapts a func that returns true if val1 < val2 and adapts it to a func(interface{}, interface{}) bool
* IntSortFunc returns true if val1.(int) < val2.(int)
* UintSortFunc returns true if val1.(uint) < val2.(uint)
* FloatSortFunc returns true if val1.(float64) < val2.(float64)
* StringSortFunc returns true if val1.(string) < val2.(string)
== Examples

=== Filter

....
var fn func(interface{}) bool = Filter(func(i int) bool { return i < 3 })
fmt.Println(fn(1), fn(5))
// true false
....

=== FilterAll

....
var filterFn []func(interface{}) bool = FilterAll(
    func(i interface{}) bool { return i.(int) < 3 },
    func(i int) bool { return i >= 0 },
)
fmt.Println(filterFns[0](1), filterFns[1](int8(-1)))
// true false
....

=== And

....
var filterFn func(interface{}) bool = And(
    func(i interface{}) bool { return i.(int) < 3 },
    func(i int) bool { return i >= 0 },
)
fmt.Println(filterFn(1), filterFn(-1))
// true false
....

=== Or

....
var filterFn func(interface{}) bool = Or(
    func(i interface{}) bool { return i.(int) < 3 },
    func(i int) bool { return i%2 == 0 },
)
fmt.Println(filterFn(1), filterFn(5))
// true false
....

=== Not

....
var filterFn func(interface{}) bool = Not(func(i interface{}) bool { return i.(int) < 3 })
fmt.Println(filterFn(1), filterFn(5))
// false true
....

=== EqualTo

....
var filterFn func(interface{}) bool = EqualTo(1)
fmt.Println(filterFn(1), filterFn(5))
// true false
....

=== IsNil

....
var filterFn func(interface{}) bool = IsNil
fmt.Println(filterFn(nil), filterFn(5))
// true false
....

=== Map

....
var fn func(interface{}) interface{} = Map(func(i int) string { return strconv.Itoa(i) })
fmt.Printf("%q, %q\n", fn(1), fn(5))
// "1" "5"
....

=== MapTo

....
var fn func(interface{}) string = MapTo(func(i int) string { return strconv.Itoa(i) }, "").(func(interface{}) string)
fmt.Printf("%q, %q\n", fn(1), fn(5))
// "1" "5"
....

=== Supplier

....
var fn func() interface{} = Suppler(func() int { return 5 })
fmt.Println(fn())
// 5

var fn func() interface{} = Suppler(func(...int) int { return 6 })
fmt.Println(fn())
// 6
....

=== SupplierOf

....
var fn func() int = SupplerOf(func() int8 { return 5 }, 0).(func() int)
fmt.Println(fn())
// 5

var fn func() int = SupplerOf(func(...int8) int8 { return 6 }, 0).(func() int)
fmt.Println(fn())
// 6
....

=== Consumer

....
var fn func(interface{}) = Consumer(func(i int) { fmt.Println(i) })
fn(5)
// 5
....

=== Ternary

....
str := "abc"
i := Ternary(str == "abc", 1, 2)
// i = 1

i = Ternary(str == "def", 1, 2)
// i = 2
....

=== Panic

....
var str string
PanicE(json.Unmarshal([]byte(`"abc"`), &str))
// str = abc

PanicE(json.Unmarshal([]byte("{"), &str))
// panics with `unexpected end of JSON input`

i := PanicVE(strconv.Atoi("1")).(int)
// i = 1

PanicVE(strconv.Atoi("a"))
// panics with `strconv.Atoi: parsing "a": invalid syntax`

PanicBM(big.NewRat(2, 1).IsInt(), "must be int")
// no panic

PanicBM(big.NewRat(2, 3).IsInt(), "must be int")
// panics with `must be an int`

f, ok := big.NewFloat(1.0).SetString("2")
PanicVBM(f, ok, "must be float64")
// f = *Float(2)

f, ok = big.NewFloat(1.0).SetString("a")
PanicVBM(f, ok, "must be float64")
// panics with `must be float64`
....

Documentation

Overview

Package gofuncs provides functions for working with functions of desired signatures SPDX-License-Identifier: Apache-2.0

Index

Constants

This section is empty.

Variables

View Source
var (
	// IntSortFunc returns true if int64 val1 < val2
	IntSortFunc = SortFunc(func(val1, val2 int64) bool {
		return val1 < val2
	})

	// UintSortFunc returns true if uint64 val1 < val2
	UintSortFunc = SortFunc(func(val1, val2 uint64) bool {
		return val1 < val2
	})

	// FloatSortFunc returns true if float64 val1 < val2
	FloatSortFunc = SortFunc(func(val1, val2 float64) bool {
		return val1 < val2
	})

	// ComplexSortFunc returns true if abs(complex128 val1) < abs(complex128 val2)
	ComplexSortFunc = SortFunc(func(val1, val2 complex128) bool {
		return cmplx.Abs(val1) < cmplx.Abs(val2)
	})

	// StringSortFunc returns true if string val1 < val2
	StringSortFunc = SortFunc(func(val1, val2 string) bool {
		return val1 < val2
	})

	// BigIntSortFunc returns true if big.Int val1 < val2
	BigIntSortFunc = SortFunc(func(val1, val2 *big.Int) bool {
		return val1.Cmp(val2) == -1
	})

	// BigRatSortFunc returns true if big.Rat val1 < val2
	BigRatSortFunc = SortFunc(func(val1, val2 *big.Rat) bool {
		return val1.Cmp(val2) == -1
	})

	// BigFloatSortFunc returns true if big.Float val1 < val2
	BigFloatSortFunc = SortFunc(func(val1, val2 *big.Float) bool {
		return val1.Cmp(val2) == -1
	})
)

Functions

func And

func And(fns ...interface{}) func(interface{}) bool

And (fns) any number of func(any)bool into the conjunction of all the funcs. Short-circuit logic will return false on the first function that returns false.

func Consumer

func Consumer(fn interface{}) func(interface{})

Consumer (fn) adapts a func(any) into a func(interface{}) If fn happens to be a func(interface{}), it is returned as is. Otherwise, each invocation converts the arg passed to the type the func receives.

func ConvertTo

func ConvertTo(out interface{}) func(interface{}) interface{}

ConvertTo generates a func(interface{}) interface{} that converts a value into the same type as the value passed. Eg, ConvertTo(int8(0)) converts a func that converts a value into an int8.

func DeepEqualTo

func DeepEqualTo(val interface{}) func(interface{}) bool

DeepEqualTo (val) returns a func(interface{}) bool that returns true if the func arg is deep equal to val. The arg is converted to the type of val first, then compared. If val is nil, then the arg type must be convertible to the type of val. If val is an untyped nil, then the arg must be an untyped nil. Comparison is made using reflect.DeepEqual.

func EqualTo

func EqualTo(val interface{}) func(interface{}) bool

EqualTo (val) returns a func(interface{}) bool that returns true if the func arg is equal to val. The arg is converted to the type of val first, then compared. If val is nil, then the arg type must be convertible to the type of val. If val is an untyped nil, then the arg must be an untyped nil. Comparison is made using == operator. If val is not comparable using == (eg, slices are not comparable), the result will be true if val and arg have the same address.

func Filter

func Filter(fn interface{}) func(interface{}) bool

Filter (fn) adapts a func(any) bool into a func(interface{}) bool. If fn happens to be a func(interface{}) bool, it is returned as is. Otherwise, each invocation converts the arg passed to the type the func receives.

func FilterAll

func FilterAll(fns ...interface{}) []func(interface{}) bool

FilterAll (fns) adapts any number of func(any) bool into a slice of func(interface{}) bool. Each func passed is separately adapted using Filter into the corresponding slice element of the result. FIlterAll is the basis for composing multiple logic functions into a single logic function. Note that when calling the provided set of logic functions, the argument type must be compatible with all of them. The most likely failure case is mixing funcs that accept interface{} that type assert the argument with funcs that accept a specific type.

func GreaterThan

func GreaterThan(val interface{}) func(val1, val2 interface{}) bool

GreaterThan (val) returns a func(val1, val2 interface{}) bool that returns true if val1 > val2. The args are converted to the type of val first, then compared. Panics if val is nil or IsLessableKind(kind of val) is false.

func GreaterThanEquals

func GreaterThanEquals(val interface{}) func(val1, val2 interface{}) bool

GreaterThanEquals (val) returns a func(val1, val2 interface{}) bool that returns true if val1 >= val2. The args are converted to the type of val first, then compared. Panics if val is nil or IsLessableKind(kind of val) is false.

func IndexOf

func IndexOf(arrslc interface{}, index uint, defalt ...interface{}) interface{}

IndexOf returns the first of the following given an array or slice, index, and optional default value: 1. slice[index] if the array or slice length > index 2. default value if provided, converted to array or slice element type 3. zero value of array or slice element type Panics if arrslc is not an array or slice. Panics if the default value is not convertible to the array or slice element type, even if it is not needed.

func IsGreaterThan

func IsGreaterThan(val interface{}) func(interface{}) bool

IsGreaterThan returns a func(arg interface{}) bool that returns true if arg > val

func IsGreaterThanEquals

func IsGreaterThanEquals(val interface{}) func(interface{}) bool

IsGreaterThanEquals returns a func(arg interface{}) bool that returns true if arg >= val

func IsLessThan

func IsLessThan(val interface{}) func(interface{}) bool

IsLessThan returns a func(arg interface{}) bool that returns true if arg < val

func IsLessThanEquals

func IsLessThanEquals(val interface{}) func(interface{}) bool

IsLessThanEquals returns a func(arg interface{}) bool that returns true if arg <= val

func IsLessableKind

func IsLessableKind(kind reflect.Kind) bool

IsLessableKind returns if if kind represents any numeric type or string

func IsNegative

func IsNegative(val interface{}) bool

IsNegative (val) returns true if the val < 0

func IsNil

func IsNil(val interface{}) bool

IsNil is a func(interface{}) bool that returns true if val is nil

func IsNilable

func IsNilable(val interface{}) bool

IsNilable is a func(interface{}) bool that returns true if val is nil or the type of val is a nilable type. Returns true of the reflect.Kind of val is Chan, Func, Interface, Map, Ptr, or Slice.

func IsNonNegative

func IsNonNegative(val interface{}) bool

IsNonNegative (val) returns true if val >= 0

func IsPositive

func IsPositive(val interface{}) bool

IsPositive (val) returns true if val > 0

func LessThan

func LessThan(val interface{}) func(val1, val2 interface{}) bool

LessThan (val) returns a func(val1, val2 interface{}) bool that returns true if val1 < val2. The args are converted to the type of val first, then compared. Panics if val is nil or IsLessableKind(kind of val) is false.

func LessThanEquals

func LessThanEquals(val interface{}) func(val1, val2 interface{}) bool

LessThanEquals (val) returns a func(val1, val2 interface{}) bool that returns true if val1 <= val2. The args are converted to the type of val first, then compared. Panics if val is nil or IsLessableKind(kind of val) is false.

func Map

func Map(fn interface{}) func(interface{}) interface{}

Map (fn) adapts a func(any) any into a func(interface{}) interface{}. If fn happens to be a func(interface{}) interface{}, it is returned as is. Otherwise, each invocation converts the arg passed to the type the func receives.

func MapTo

func MapTo(fn interface{}, val interface{}) interface{}

MapTo (fn, X) adapts a func(any) X' into a func(interface{}) X. If fn happens to be a func(interface{}) X, it is returned as is. Otherwise, each invocation converts the arg passed to the type the func receives, and type X' must be convertible to X. The result will have to be type asserted by the caller.

func Not

func Not(fn interface{}) func(interface{}) bool

Not (fn) adapts a func(any) bool to the negation of the func.

func Or

func Or(fns ...interface{}) func(interface{}) bool

Or (fns) any number of func(any)bool into the disjunction of all the funcs. Short-circuit logic will return true on the first function that returns true.

func PanicBM

func PanicBM(valid bool, msg string)

PanicBM panics with msg if valid is false

func PanicE

func PanicE(err error)

PanicE panics if err is non-nil

func PanicVBM

func PanicVBM(val interface{}, valid bool, msg string) interface{}

PanicVBM panics with msg if valid is false, else returns val

func PanicVE

func PanicVE(val interface{}, err error) interface{}

PanicVE panics if err is non-nil, otherwise returns val

func SortFunc

func SortFunc(fn interface{}) func(val1, val2 interface{}) bool

SortFunc adapts a func(val1, val2 any) bool into a func(val1, val2 interface{}) bool. If fn is already a func(val1, val2 interface{}) bool, it is returned as is. The passed func must return true if and only if val1 < val2. Panics if fn is nil, not a func, does not accept two args of the same type, or does not return a single bool value.

func Supplier

func Supplier(fn interface{}) func() interface{}

Supplier (fn) adapts a func() any into a func() interface{}. If fn happens to be a func() interface{}, it is returned as is. fn may have a single variadic argument.

func SupplierOf

func SupplierOf(fn interface{}, val interface{}) interface{}

SupplierOf (fn, X) adapts a func() X' into a func() X. If fn happens to be a func() X, it is returned as is. Otherwise, type X' must be convertible to X. The result will have to be type asserted by the caller. fn may have a single variadic argument.

func Ternary

func Ternary(expr bool, trueVal, falseVal interface{}) interface{}

Ternary returns trueVal if expr is true, else it returns falseVal

func TernaryOf

func TernaryOf(expr bool, trueVal, falseVal interface{}) interface{}

TernaryOf returns trueVal() if expr is true, else it returns falseVal() trueVal and falseVal must be func() any.

func ValueOfKey

func ValueOfKey(mp interface{}, key interface{}, defalt ...interface{}) interface{}

ValueOfKey returns the first of the following: 1. map[key] if the key exists in the map 2. default if provided 3. zero value of map value type Panics if mp is not a map. Panics if the default value is not convertible to map value type, even if it is not needed.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL