1 ## our_shell: ysh
2 ## oils_failures_allowed: 3
3
4 #### Object() creates prototype chain
5
6 func Rect_area(this) {
7 return (this.x * this.y)
8 }
9
10 var Rect = Object(null, {area: Rect_area})
11
12 var rect1 = Object(Rect, {x: 3, y: 4})
13 var rect2 = Object(Rect, {x: 10, y: 20})
14
15 # This could change to show the object?
16 # pp test_ (rect)
17
18 # TODO: This should be a bound function
19 #pp asdl_ (rect)
20 #pp (rect.area)
21 #pp (rect->area)
22
23 var area1 = rect1.area()
24 var area2 = rect2.area()
25
26 pp test_ ([rect1.x, rect1.y])
27 echo "area1 = $area1"
28
29 pp test_ ([rect2.x, rect2.y])
30 echo "area2 = $area2"
31
32 #pp test_ (rect1.nonexistent)
33
34 ## STDOUT:
35 (List) [3,4]
36 area1 = 12
37 (List) [10,20]
38 area2 = 200
39 ## END
40
41 #### prototype()
42
43 func Rect_area(this) {
44 return (this.x * this.y)
45 }
46
47 var Rect = Object(null, {area: Rect_area})
48
49 var obj = Object(Rect, {x: 3, y: 4})
50
51 pp test_ (prototype(Rect))
52 pp test_ (prototype(obj))
53
54 ## STDOUT:
55 ## END
56
57 #### Copy to Dict with dict(), and mutate
58
59 var rect = Object(null, {x: 3, y: 4})
60 var d = dict(rect)
61
62 pp test_ (rect)
63 pp test_ (d)
64
65 # Right now, object attributes aren't mutable! Could change this.
66 #
67 setvar rect.x = 99
68 setvar d.x = 100
69
70 pp test_ (rect)
71 pp test_ (d)
72 ## STDOUT:
73 (Obj) {"x":3,"y":4}
74 (Dict) {"x":3,"y":4}
75 (Obj) {"x":99,"y":4}
76 (Dict) {"x":100,"y":4}
77 ## END
78
79 #### setvar obj.attr = and += and ...
80
81 var rect = Object(null, {x: 3, y: 4})
82 pp test_ (rect)
83
84 setvar rect.y = 99
85 pp test_ (rect)
86
87 setvar rect.y += 3
88 pp test_ (rect)
89
90 setvar rect.x *= 5
91 pp test_ (rect)
92
93 ## STDOUT:
94 (Obj) {"x":3,"y":4}
95 (Obj) {"x":3,"y":99}
96 (Obj) {"x":3,"y":102}
97 (Obj) {"x":15,"y":102}
98 ## END
99
100 #### can't encode objects as JSON
101
102 var Rect = Object(null, {})
103
104 json write (Rect)
105 echo 'nope'
106
107 ## status: 1
108 ## STDOUT:
109 ## END
110
111 #### pretty printing of cycles
112
113 var d = {k: 42}
114 setvar d.cycle = d
115
116 pp test_ (d)
117
118 var o = Object(null, d)
119
120 pp test_ (o)
121
122 var o2 = Object(o, {z: 99})
123
124 pp test_ (o2)
125
126 ## STDOUT:
127 ## END
128
129 #### Can all builtin methods with s.upper()
130
131 var s = 'foo'
132 var x = s.upper()
133 var y = "--$[x.lower()]"
134
135 pp test_ (x)
136 pp test_ (y)
137
138 ## STDOUT:
139 (Str) "FOO"
140 (Str) "--foo"
141 ## END
142
143
144 #### Dict.keys(d), Dict.values(d), Dict.get(d, key)
145
146 var d = {a: 42, b: 99}
147
148 pp test_ (Dict.keys(d))
149 pp test_ (Dict.values(d))
150
151 pp test_ (Dict.get(d, 'key', 'default'))
152
153 # mutating methods are OK?
154 # call d->inc(x)
155
156 ## STDOUT:
157 ## END
158