Added Min, Max and improved Bool

This commit is contained in:
Rnhmjoj 2014-03-01 16:48:45 +01:00
parent e26a8a8828
commit 9620206ee8
3 changed files with 90 additions and 9 deletions

View File

@ -9,11 +9,10 @@ func Bool(x interface{}) bool {
}
vx := reflect.ValueOf(x)
switch vx.Kind() {
case reflect.Bool: {
case reflect.Bool:
if vx.Bool() {
return true
}
}
case reflect.Int, reflect.Int8,
reflect.Int16, reflect.Int32,
reflect.Int64:
@ -30,12 +29,8 @@ func Bool(x interface{}) bool {
if vx.Float() == 0.0 {
return false
}
case reflect.String:
if vx.String() == "" {
return false
}
case reflect.Array, reflect.Slice,
reflect.Map:
reflect.Map, reflect.String:
if vx.Len() == 0 {
return false
}

View File

@ -64,4 +64,88 @@ func Open(args...string) *os.File{
return file
}
//TODO min, max
func less(a, b interface{}) bool {
va := reflect.ValueOf(a)
vb := reflect.ValueOf(b)
switch va.Kind() {
case reflect.Bool:
if va.Bool() == false && vb.Bool() == true{
return true
}
case reflect.Int, reflect.Int8,
reflect.Int16, reflect.Int32,
reflect.Int64:
if va.Int() < vb.Int() {
return true
}
case reflect.Uint, reflect.Uint8,
reflect.Uint16, reflect.Uint32,
reflect.Uint64:
if va.Uint() < vb.Uint() {
return true
}
case reflect.Float32, reflect.Float64:
if va.Float() < vb.Float() {
return true
}
case reflect.Array, reflect.Slice,
reflect.Map, reflect.String:
if va.Len() < vb.Len() {
return true
}
default:
panic("Unsupported type")
}
return false
}
func min(iter interface{}) interface{} {
viter := reflect.ValueOf(iter)
min := viter.Index(0).Interface()
for i := 0; i < viter.Len(); i++ {
if less(viter.Index(i).Interface(), min){
min = viter.Index(i).Interface()
}
}
return min
}
func max(iter interface{}) interface{} {
viter := reflect.ValueOf(iter)
max := viter.Index(0).Interface()
for i := 0; i < viter.Len(); i++ {
if less(max, viter.Index(i).Interface()){
max = viter.Index(i).Interface()
}
}
return max
}
func Min(args... interface{}) interface{}{
x := len(args)
switch {
case x == 1:
return min(args[0])
case x > 1:
return min(args)
default:
panic("Min accepts 1 or more arguments")
}
}
func Max(args... interface{}) interface{}{
x := len(args)
switch {
case x == 1:
return max(args[0])
case x > 1:
return max(args)
default:
panic("Min accepts 1 or more arguments")
}
}

View File

@ -16,9 +16,11 @@ func main(){
Abs(-19.3),
Pow(2,16),
Type(true),
Open("ciao2.txt", "a"),
Open("test.txt", "a+"),
Any([]interface{}{0, 1, []int{}, ""}),
All([]interface{}{true,"",1}),
Min([]float64{3.14159,23.14069,2.71828}),
Max(-3,24,1,-23,31),
Input("Scrivi qualcosa: "),
}
fmt.Println(test)