aboutsummaryrefslogtreecommitdiff
path: root/spec/inputs/test/with_spec.yue
blob: 70b50ee0e51bff2642805bbab4dba64359aebadd (plain)
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
describe "with", ->
	it "should access property with . syntax", ->
		obj = {value: 42}
		with obj
			result = .value
			assert.same result, 42

	it "should call method with : syntax", ->
		obj = {func: -> "result"}
		with obj
			result = \func!
			assert.same result, "result"

	it "should work as statement", ->
		obj = {x: 10, y: 20}
		with obj
			.sum = .x + .y
		assert.same obj.sum, 30

	it "should support nested with", ->
		outer = {inner: {value: 100}}
		with outer.inner
			result = .value
			assert.same result, 100

	it "should work with? safely", ->
		obj = {x: 5}
		with obj
			result = .x
			assert.same result, 5

	it "should work with if inside with", ->
		obj = {x: 10, y: 20}
		with obj
			if .x > 5
				result = .x + .y
				assert.same result, 30

	it "should work with switch inside with", ->
		obj = {type: "add", a: 5, b: 3}
		with obj
			result = switch .type
				when "add" then .a + .b
				else 0
			assert.same result, 8

	it "should work with loop inside with", ->
		obj = {items: {1, 2, 3}}
		sum = 0
		with obj
			for item in *.items
				sum += item
		assert.same sum, 6

	it "should work with destructure", ->
		obj = {x: 1, y: 2, z: 3}
		with {:x, :y, :z} := obj
			assert.same x, 1
			assert.same y, 2
			assert.same z, 3

	it "should handle simple with body", ->
		obj = {value: 42}
		with obj
			.value2 = 100
		assert.same obj.value2, 100

	it "should work with return inside", ->
		obj = {value: 100}
		fn = ->
			with obj
				return .value
		assert.same fn!, 100

	it "should work with break inside", ->
		sum = 0
		for i = 1, 5
			obj = {value: i}
			with obj
				if .value == 3
					break
				sum += .value
		assert.same sum, 3  -- 1 + 2

	it "should chain property access", ->
		obj = {a: {b: {c: 42}}}
		with obj.a.b
			result = .c
			assert.same result, 42

	it "should work with multiple statements", ->
		obj = {x: 1, y: 2}
		sum = 0
		with obj
			sum += .x
			sum += .y
		assert.same sum, 3

	it "should preserve object reference", ->
		obj = {value: 42}
		with obj
			.value = 100
		assert.same obj.value, 100