2015-02-16 15:28:33 +02:00
|
|
|
package otto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"math"
|
|
|
|
"reflect"
|
2017-02-16 15:21:11 +03:00
|
|
|
"unicode/utf16"
|
2015-02-16 15:28:33 +02:00
|
|
|
)
|
|
|
|
|
2015-03-20 14:22:01 +02:00
|
|
|
func (value Value) bool() bool {
|
|
|
|
if value.kind == valueBoolean {
|
2015-02-16 15:28:33 +02:00
|
|
|
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)
|
2017-02-16 15:21:11 +03:00
|
|
|
case []uint16:
|
|
|
|
return 0 != len(utf16.Decode(value))
|
2015-02-16 15:28:33 +02:00
|
|
|
}
|
|
|
|
if value.IsObject() {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
panic(fmt.Errorf("toBoolean(%T)", value.value))
|
|
|
|
}
|