forked from robertkrimen/otto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
documentation_test.go
141 lines (123 loc) · 2.49 KB
/
documentation_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package otto
import (
"fmt"
"os"
)
func ExampleSynopsis() { //nolint: govet
vm := New()
_, err := vm.Run(`
abc = 2 + 2;
console.log("The value of abc is " + abc); // 4
`)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
value, err := vm.Get("abc")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
iv, err := value.ToInteger()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(iv)
err = vm.Set("def", 11)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
_, err = vm.Run(`
console.log("The value of def is " + def);
`)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
err = vm.Set("xyzzy", "Nothing happens.")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
_, err = vm.Run(`
console.log(xyzzy.length);
`)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
value, err = vm.Run("xyzzy.length")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
iv, err = value.ToInteger()
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(iv)
value, err = vm.Run("abcdefghijlmnopqrstuvwxyz.length")
fmt.Println(value)
fmt.Println(err) // Expected error.
err = vm.Set("sayHello", func(call FunctionCall) Value {
fmt.Printf("Hello, %s.\n", call.Argument(0).String())
return UndefinedValue()
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
err = vm.Set("twoPlus", func(call FunctionCall) Value {
right, _ := call.Argument(0).ToInteger()
result, _ := vm.ToValue(2 + right)
return result
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
value, err = vm.Run(`
sayHello("Xyzzy");
sayHello();
result = twoPlus(2.0);
`)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Println(value)
// Output:
// The value of abc is 4
// 4
// The value of def is 11
// 16
// 16
// undefined
// ReferenceError: 'abcdefghijlmnopqrstuvwxyz' is not defined
// Hello, Xyzzy.
// Hello, undefined.
// 4
}
func ExampleConsole() { //nolint: govet
vm := New()
console := map[string]interface{}{
"log": func(call FunctionCall) Value {
fmt.Println("console.log:", formatForConsole(call.ArgumentList))
return UndefinedValue()
},
}
err := vm.Set("console", console)
if err != nil {
panic(fmt.Errorf("console error: %w", err))
}
value, err := vm.Run(`console.log("Hello, World.");`)
fmt.Println(value)
fmt.Println(err)
// Output:
// console.log: Hello, World.
// undefined
// <nil>
}