value_boolean.go 754 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package otto
  2. import (
  3. "fmt"
  4. "math"
  5. "reflect"
  6. "unicode/utf16"
  7. )
  8. func (v Value) bool() bool {
  9. if v.kind == valueBoolean {
  10. return v.value.(bool)
  11. }
  12. if v.IsUndefined() || v.IsNull() {
  13. return false
  14. }
  15. switch value := v.value.(type) {
  16. case bool:
  17. return value
  18. case int, int8, int16, int32, int64:
  19. return reflect.ValueOf(value).Int() != 0
  20. case uint, uint8, uint16, uint32, uint64:
  21. return reflect.ValueOf(value).Uint() != 0
  22. case float32:
  23. return value != 0
  24. case float64:
  25. if math.IsNaN(value) || value == 0 {
  26. return false
  27. }
  28. return true
  29. case string:
  30. return len(value) != 0
  31. case []uint16:
  32. return len(utf16.Decode(value)) != 0
  33. }
  34. if v.IsObject() {
  35. return true
  36. }
  37. panic(fmt.Sprintf("unexpected boolean type %T", v.value))
  38. }