1
0
mirror of https://github.com/robertkrimen/otto synced 2025-10-19 19:55:30 +08:00
otto/value_boolean.go
Robert Krimen 918abeb8d8 The zero value of Value is now defined to be undefined
Previously, it was a publically accessible but invalid value (valueEmpty).

* Deprecate internal use of UndefinedValue(), NullValue(), FalseValue(), TrueValue()
* Guard against Empty, Result, Reference values from escaping the package
2014-05-28 21:23:32 -07:00

50 lines
901 B
Go

package otto
import (
"fmt"
"math"
"reflect"
)
func toBoolean(value Value) bool {
if value.kind == valueBoolean {
return value.value.(bool)
}
if value.IsUndefined() {
return false
}
if value.IsNull() {
return false
}
switch value := value.value.(type) {
case bool:
return value
case int, int8, int16, int32, int64:
return 0 != reflect.ValueOf(value).Int()
case uint, uint8, uint16, uint32, uint64:
return 0 != reflect.ValueOf(value).Uint()
case float32:
return 0 != value
case float64:
if math.IsNaN(value) || value == 0 {
return false
}
return true
case string:
return 0 != len(value)
}
if value.IsObject() {
return true
}
panic(fmt.Errorf("toBoolean(%T)", value.value))
}
func stringToBoolean(value string) bool {
if value == "true" {
return true
} else if value == "false" {
return false
}
panic(fmt.Errorf("stringToBoolean(%s)", value))
}