-
Notifications
You must be signed in to change notification settings - Fork 1
/
inRange.go
102 lines (81 loc) · 2.37 KB
/
inRange.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package number
import (
"reflect"
"github.com/warriors-vn/go-dash/constants"
)
// InRange checks if a given number is within the specified range [start, end).
// The function accepts three arguments: number, start, and end, all of type interface{}.
// It returns a boolean indicating whether the number is within the range and an error if any issue occurs.
func InRange(number, start interface{}, end ...interface{}) (bool, error) {
typeOfNumber, typeOfStart := reflect.TypeOf(number), reflect.TypeOf(start)
var endRange interface{}
if end != nil {
endRange = end[0]
if !(typeOfNumber.Kind() == typeOfStart.Kind() && typeOfNumber.Kind() == reflect.TypeOf(endRange).Kind()) {
return false, constants.ErrIncompatible
}
} else {
endRange, start = start, endRange
if !(typeOfNumber.Kind() == reflect.TypeOf(endRange).Kind()) {
return false, constants.ErrIncompatible
}
}
switch typeOfNumber.Kind() {
case reflect.Int:
if start == nil {
start = 0
}
if resultStart, ok := start.(int); ok && number.(int) <= resultStart {
return false, nil
}
if resultEnd, ok := endRange.(int); ok && number.(int) >= resultEnd {
return false, nil
}
return true, nil
case reflect.Int32:
if start == nil {
start = int32(0)
}
if resultStart, ok := start.(int32); ok && number.(int32) <= resultStart {
return false, nil
}
if resultEnd, ok := endRange.(int32); ok && number.(int32) >= resultEnd {
return false, nil
}
return true, nil
case reflect.Int64:
if start == nil {
start = int64(0)
}
if resultStart, ok := start.(int64); ok && number.(int64) <= resultStart {
return false, nil
}
if resultEnd, ok := endRange.(int64); ok && number.(int64) >= resultEnd {
return false, nil
}
return true, nil
case reflect.Float32:
if start == nil {
start = float32(0)
}
if resultStart, ok := start.(float32); ok && number.(float32) <= resultStart {
return false, nil
}
if resultEnd, ok := endRange.(float32); ok && number.(float32) >= resultEnd {
return false, nil
}
return true, nil
case reflect.Float64:
if start == nil {
start = float64(0)
}
if resultStart, ok := start.(float64); ok && number.(float64) <= resultStart {
return false, nil
}
if resultEnd, ok := endRange.(float64); ok && number.(float64) >= resultEnd {
return false, nil
}
return true, nil
}
return false, constants.ErrNotSupport
}