Skip to content

Commit

Permalink
Fix abs() for positive numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
antonmedv committed Feb 3, 2023
1 parent 2992aac commit d8586f1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
1 change: 1 addition & 0 deletions builtin/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ var tests = []struct {
{`len({foo: 1, bar: 2})`, 2},
{`len("hello")`, 5},
{`abs(-5)`, 5},
{`abs(.5)`, .5},
{`abs(-.5)`, .5},
{`int(5.5)`, 5},
{`int(5)`, 5},
Expand Down
24 changes: 24 additions & 0 deletions vm/runtime/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,50 +431,74 @@ func Abs(x interface{}) interface{} {
case float32:
if x.(float32) < 0 {
return -x.(float32)
} else {
return x
}
case float64:
if x.(float64) < 0 {
return -x.(float64)
} else {
return x
}
case int:
if x.(int) < 0 {
return -x.(int)
} else {
return x
}
case int8:
if x.(int8) < 0 {
return -x.(int8)
} else {
return x
}
case int16:
if x.(int16) < 0 {
return -x.(int16)
} else {
return x
}
case int32:
if x.(int32) < 0 {
return -x.(int32)
} else {
return x
}
case int64:
if x.(int64) < 0 {
return -x.(int64)
} else {
return x
}
case uint:
if x.(uint) < 0 {
return -x.(uint)
} else {
return x
}
case uint8:
if x.(uint8) < 0 {
return -x.(uint8)
} else {
return x
}
case uint16:
if x.(uint16) < 0 {
return -x.(uint16)
} else {
return x
}
case uint32:
if x.(uint32) < 0 {
return -x.(uint32)
} else {
return x
}
case uint64:
if x.(uint64) < 0 {
return -x.(uint64)
} else {
return x
}
}
panic(fmt.Sprintf("invalid argument for abs (type %T)", x))
Expand Down

0 comments on commit d8586f1

Please sign in to comment.