github.com/nuvolaris/goja@v0.0.0-20230825100449-967811910c6d/builtin_boolean.go (about)

     1  package goja
     2  
     3  func (r *Runtime) booleanproto_toString(call FunctionCall) Value {
     4  	var b bool
     5  	switch o := call.This.(type) {
     6  	case valueBool:
     7  		b = bool(o)
     8  		goto success
     9  	case *Object:
    10  		if p, ok := o.self.(*primitiveValueObject); ok {
    11  			if b1, ok := p.pValue.(valueBool); ok {
    12  				b = bool(b1)
    13  				goto success
    14  			}
    15  		}
    16  		if o, ok := o.self.(*objectGoReflect); ok {
    17  			if o.class == classBoolean && o.toString != nil {
    18  				return o.toString()
    19  			}
    20  		}
    21  	}
    22  	r.typeErrorResult(true, "Method Boolean.prototype.toString is called on incompatible receiver")
    23  
    24  success:
    25  	if b {
    26  		return stringTrue
    27  	}
    28  	return stringFalse
    29  }
    30  
    31  func (r *Runtime) booleanproto_valueOf(call FunctionCall) Value {
    32  	switch o := call.This.(type) {
    33  	case valueBool:
    34  		return o
    35  	case *Object:
    36  		if p, ok := o.self.(*primitiveValueObject); ok {
    37  			if b, ok := p.pValue.(valueBool); ok {
    38  				return b
    39  			}
    40  		}
    41  		if o, ok := o.self.(*objectGoReflect); ok {
    42  			if o.class == classBoolean && o.valueOf != nil {
    43  				return o.valueOf()
    44  			}
    45  		}
    46  	}
    47  
    48  	r.typeErrorResult(true, "Method Boolean.prototype.valueOf is called on incompatible receiver")
    49  	return nil
    50  }
    51  
    52  func (r *Runtime) initBoolean() {
    53  	r.global.BooleanPrototype = r.newPrimitiveObject(valueFalse, r.global.ObjectPrototype, classBoolean)
    54  	o := r.global.BooleanPrototype.self
    55  	o._putProp("toString", r.newNativeFunc(r.booleanproto_toString, nil, "toString", nil, 0), true, false, true)
    56  	o._putProp("valueOf", r.newNativeFunc(r.booleanproto_valueOf, nil, "valueOf", nil, 0), true, false, true)
    57  
    58  	r.global.Boolean = r.newNativeFunc(r.builtin_Boolean, r.builtin_newBoolean, "Boolean", r.global.BooleanPrototype, 1)
    59  	r.addToGlobal("Boolean", r.global.Boolean)
    60  }