}
}
+// Truthy returns the JavaScript "truthiness" of the value v. In JavaScript,
+// false, 0, "", null, undefined, and NaN are "falsy", and everything else is
+// "truthy". See https://developer.mozilla.org/en-US/docs/Glossary/Truthy.
+func (v Value) Truthy() bool {
+ switch v.Type() {
+ case TypeUndefined, TypeNull:
+ return false
+ case TypeBoolean:
+ return v.Bool()
+ case TypeNumber:
+ return v.ref != valueNaN.ref && v.ref != valueZero.ref
+ case TypeString:
+ return v.String() != ""
+ case TypeSymbol, TypeFunction, TypeObject:
+ return true
+ default:
+ panic("bad type")
+ }
+}
+
// String returns the value v converted to string according to JavaScript type conversions.
func (v Value) String() string {
str, length := valuePrepareString(v.ref)
// +build js,wasm
+// To run these tests:
+//
+// - Install Node
+// - Add /path/to/go/misc/wasm to your $PATH (so that "go test" can find
+// "go_js_wasm_exec").
+// - GOOS=js GOARCH=wasm go test
+//
+// See -exec in "go help test", and "go help run" for details.
+
package js_test
import (
someInt: 42,
someFloat: 42.123,
someArray: [41, 42, 43],
+ someDate: new Date(),
add: function(a, b) {
return a + b;
},
zero: 0,
+ stringZero: "0",
NaN: NaN,
+ emptyObj: {},
+ emptyArray: [],
+ Infinity: Infinity,
+ NegInfinity: -Infinity,
+ objNumber0: new Number(0),
+ objBooleanFalse: new Boolean(false),
})`)
func TestBool(t *testing.T) {
})
js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb)
}
+
+// See
+// - https://developer.mozilla.org/en-US/docs/Glossary/Truthy
+// - https://stackoverflow.com/questions/19839952/all-falsey-values-in-javascript/19839953#19839953
+// - http://www.ecma-international.org/ecma-262/5.1/#sec-9.2
+func TestTruthy(t *testing.T) {
+ want := true
+ for _, key := range []string{
+ "someBool", "someString", "someInt", "someFloat", "someArray", "someDate",
+ "stringZero", // "0" is truthy
+ "add", // functions are truthy
+ "emptyObj", "emptyArray", "Infinity", "NegInfinity",
+ // All objects are truthy, even if they're Number(0) or Boolean(false).
+ "objNumber0", "objBooleanFalse",
+ } {
+ if got := dummys.Get(key).Truthy(); got != want {
+ t.Errorf("%s: got %#v, want %#v", key, got, want)
+ }
+ }
+
+ want = false
+ if got := dummys.Get("zero").Truthy(); got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+ if got := dummys.Get("NaN").Truthy(); got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+ if got := js.ValueOf("").Truthy(); got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+ if got := js.Null().Truthy(); got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+ if got := js.Undefined().Truthy(); got != want {
+ t.Errorf("got %#v, want %#v", got, want)
+ }
+}