-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
Showing
2 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |