@@ -22,27 +22,23 @@ const (
22
22
TypeFunction
23
23
)
24
24
25
+ // Same order as Type constants
26
+ var typeNames = []string {
27
+ "undefined" ,
28
+ "null" ,
29
+ "boolean" ,
30
+ "number" ,
31
+ "string" ,
32
+ "symbol" ,
33
+ "object" ,
34
+ "function" ,
35
+ }
36
+
25
37
func (t Type ) String () string {
26
- switch t {
27
- case TypeUndefined :
28
- return "undefined"
29
- case TypeNull :
30
- return "null"
31
- case TypeBoolean :
32
- return "boolean"
33
- case TypeNumber :
34
- return "number"
35
- case TypeString :
36
- return "string"
37
- case TypeSymbol :
38
- return "symbol"
39
- case TypeObject :
40
- return "object"
41
- case TypeFunction :
42
- return "function"
43
- default :
38
+ if int (t ) < 0 || len (typeNames ) <= int (t ) {
44
39
panic ("bad type" )
45
40
}
41
+ return typeNames [t ]
46
42
}
47
43
48
44
func (t Type ) isObject () bool {
@@ -110,40 +106,30 @@ func objectToValue(obj *js.Object) Value {
110
106
}
111
107
112
108
var (
113
- id * js.Object
114
- instanceOf * js.Object
115
- getValueType * js.Object
109
+ id * js.Object
110
+ instanceOf * js.Object
111
+ typeOf * js.Object
116
112
)
117
113
118
114
func init () {
119
115
if js .Global != nil {
120
- id = js .Global .Call ("Function" , "x" , "return x" )
121
- instanceOf = js .Global .Call ("Function" , "x" , "y" , "return x instanceof y" )
122
- getValueType = js .Global .Call ("Function" , "x" , `
123
- if (typeof(x) === "undefined") {
124
- return 0; // TypeUndefined
125
- }
126
- if (x === null) {
127
- return 1; // TypeNull
128
- }
129
- if (typeof(x) === "boolean") {
130
- return 2; // TypeBoolean
131
- }
132
- if (typeof(x) === "number") {
133
- return 3; // TypeNumber
134
- }
135
- if (typeof(x) === "string") {
136
- return 4; // TypeString
137
- }
138
- if (typeof(x) === "symbol") {
139
- return 5; // TypeSymbol
140
- }
141
- if (typeof(x) === "function") {
142
- return 7; // TypeFunction
143
- }
144
- return 6; // TypeObject
145
- ` )
116
+ id = js .Global .Get ("$id" )
117
+ instanceOf = js .Global .Get ("$instanceOf" )
118
+ typeOf = js .Global .Get ("$typeOf" )
119
+ }
120
+ }
121
+
122
+ func getValueType (obj * js.Object ) Type {
123
+ if obj == nil {
124
+ return TypeNull
125
+ }
126
+ name := typeOf .Invoke (obj ).String ()
127
+ for type2 , name2 := range typeNames {
128
+ if name == name2 {
129
+ return Type (type2 )
130
+ }
146
131
}
132
+ return TypeObject
147
133
}
148
134
149
135
func ValueOf (x interface {}) Value {
@@ -322,7 +308,7 @@ func (v Value) Truthy() bool {
322
308
}
323
309
324
310
func (v Value ) Type () Type {
325
- return Type (getValueType . Invoke (v .internal ()). Int ( ))
311
+ return Type (getValueType (v .internal ()))
326
312
}
327
313
328
314
func (v Value ) IsNull () bool {
0 commit comments