MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1// Test 1: Basic shadowing in nested scopes
2let x = "outer";
3{
4 let x = "inner";
5 console.log(x); // Should print "inner"
6}
7console.log(x); // Should print "outer"
8
9// Test 2: Closure capturing outer scope
10let y = 10;
11function makeCounter() {
12 let count = 0;
13 return function() {
14 count = count + 1;
15 return count + y; // Access both local and outer scope
16 };
17}
18let counter = makeCounter();
19console.log(counter()); // Should print 11
20console.log(counter()); // Should print 12
21
22// Test 3: Variable shadowing in function
23let z = "global";
24function testShadow() {
25 let z = "local";
26 return z;
27}
28console.log(testShadow()); // Should print "local"
29console.log(z); // Should print "global"
30
31// Test 4: Nested function closures
32function outer() {
33 let a = 1;
34 function middle() {
35 let b = 2;
36 function inner() {
37 let c = 3;
38 return a + b + c; // Access all three scopes
39 }
40 return inner();
41 }
42 return middle();
43}
44console.log(outer()); // Should print 6
45
46// Test 5: Multiple closures sharing same outer scope
47function makeCounters() {
48 let shared = 0;
49 return {
50 inc: function() { shared = shared + 1; return shared; },
51 dec: function() { shared = shared - 1; return shared; },
52 get: function() { return shared; }
53 };
54}
55let counters = makeCounters();
56console.log(counters.inc()); // Should print 1
57console.log(counters.inc()); // Should print 2
58console.log(counters.dec()); // Should print 1
59console.log(counters.get()); // Should print 1