Skip to content

Commit

Permalink
Pull request: add-algo
Browse files Browse the repository at this point in the history
Merge in DNS/golibs from add-algo to master

Squashed commit of the following:

commit c48a311
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Tue Jan 24 16:12:43 2023 +0300

    mathutil: rename from algo; imp; rm Abs

commit 416e092
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Jan 23 19:12:53 2023 +0300

    algo: add pkg
  • Loading branch information
ainar-g committed Jan 24, 2023
1 parent 99723cc commit ea372db
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
37 changes: 37 additions & 0 deletions mathutil/mathutil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Package mathutil contains generic helpers for common algorithms and
// mathematic operations.
package mathutil

import "golang.org/x/exp/constraints"

// Number is a type constraint for all numbers.
type Number interface {
constraints.Integer | constraints.Float
}

// BoolToNumber returns 1 if cond is true and 0 otherwise.
func BoolToNumber[T Number](cond bool) (res T) {
if cond {
return 1
}

return 0
}

// Max returns the larger of x or y.
func Max[T constraints.Integer | ~string](x, y T) (res T) {
if x > y {
return x
}

return y
}

// Min returns the smaller of x or y.
func Min[T constraints.Integer | ~string](x, y T) (res T) {
if x < y {
return x
}

return y
}
40 changes: 40 additions & 0 deletions mathutil/mathutil_example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package mathutil_test

import (
"fmt"

"github.com/AdguardTeam/golibs/mathutil"
)

func ExampleBoolToNumber() {
fmt.Println(mathutil.BoolToNumber[int](true))
fmt.Println(mathutil.BoolToNumber[int](false))

type flag float64
fmt.Println(mathutil.BoolToNumber[flag](true))
fmt.Println(mathutil.BoolToNumber[flag](false))

// Output:
// 1
// 0
// 1
// 0
}

func ExampleMax() {
fmt.Println(mathutil.Max(1, 2))
fmt.Println(mathutil.Max(2, 1))

// Output:
// 2
// 2
}

func ExampleMin() {
fmt.Println(mathutil.Min(1, 2))
fmt.Println(mathutil.Min(2, 1))

// Output:
// 1
// 1
}

0 comments on commit ea372db

Please sign in to comment.