Skip to content

Commit

Permalink
Merge pull request #3 from lovung/feature/Add-num-package-to-help-pro…
Browse files Browse the repository at this point in the history
…cess-num-values

Add num package to help processing num values
  • Loading branch information
lovung authored Nov 29, 2020
2 parents 98d1091 + 2180f55 commit 2453db9
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
37 changes: 37 additions & 0 deletions num/int.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package num

// Sign of a integer
// 1 for positive
// 0 for zero
// -1 for negative
func Sign(num int) int {
if num < 0 {
return -1
}
if num > 0 {
return +1
}
return 0
}

// MaxInt is compares and returns the larger one.
func MaxInt(first int, rest ...int) int {
ans := first
for _, item := range rest {
if item > ans {
ans = item
}
}
return ans
}

// MinInt is compares and returns the lesser one.
func MinInt(first int, rest ...int) int {
ans := first
for _, item := range rest {
if item < ans {
ans = item
}
}
return ans
}
75 changes: 75 additions & 0 deletions num/int_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package num

import "testing"

func TestSign(t *testing.T) {
type args struct {
num int
}
tests := []struct {
name string
args args
want int
}{
{args: args{-12}, want: -1},
{args: args{-6}, want: -1},
{args: args{0}, want: 0},
{args: args{6}, want: 1},
{args: args{12}, want: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Sign(tt.args.num); got != tt.want {
t.Errorf("Sign() = %v, want %v", got, tt.want)
}
})
}
}

func TestMaxInt(t *testing.T) {
type args struct {
first int
rest []int
}
tests := []struct {
name string
args args
want int
}{
{args: args{0, []int{-1, -2, -3, -4, -5}}, want: 0},
{args: args{12, []int{-1, -2, -3, -4, -5}}, want: 12},
{args: args{-12, []int{-1, -2, -3, -4, -5}}, want: -1},
{args: args{0, []int{1, 2, 3, 4, 5}}, want: 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := MaxInt(tt.args.first, tt.args.rest...); got != tt.want {
t.Errorf("MaxInt() = %v, want %v", got, tt.want)
}
})
}
}

func TestMinInt(t *testing.T) {
type args struct {
first int
rest []int
}
tests := []struct {
name string
args args
want int
}{
{args: args{0, []int{-1, -2, -3, -4, -5}}, want: -5},
{args: args{12, []int{-1, -2, -3, -4, -5}}, want: -5},
{args: args{-12, []int{-1, -2, -3, -4, -5}}, want: -12},
{args: args{0, []int{1, 2, 3, 4, 5}}, want: 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := MinInt(tt.args.first, tt.args.rest...); got != tt.want {
t.Errorf("MinInt() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 2453db9

Please sign in to comment.