tsrun 0.1.23

A TypeScript interpreter designed for embedding in applications
Documentation
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
//! Array-related tests

use super::{eval, eval_result};
use tsrun::JsValue;
use tsrun::value::JsString;

#[test]
fn test_array() {
    assert_eq!(eval("const arr = [1, 2, 3]; arr[1]"), JsValue::Number(2.0));
}

// Debug test to understand map issue
#[test]
fn test_debug_map_step_by_step() {
    // Step 1: Test callback is called
    assert_eq!(
        eval("let r = 0; [1].map(x => { r = x * 2; }); r"),
        JsValue::Number(2.0),
        "Callback should be called and set r"
    );

    // Step 2: Test that map returns something
    let result = eval("[1].map(x => x * 2)");
    println!("map result: {:?}", result);
    // assert it's an object (array)

    // Step 2b: Test length directly on result
    assert_eq!(
        eval("[1].map(x => x * 2).length"),
        JsValue::Number(1.0),
        "Mapped array should have length 1"
    );
}

// Array.prototype.push tests
#[test]
fn test_array_push_single() {
    assert_eq!(
        eval("const arr = [1, 2]; arr.push(3); arr.length"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_push_returns_length() {
    assert_eq!(
        eval("const arr = [1, 2]; arr.push(3)"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_push_multiple() {
    assert_eq!(
        eval("const arr = [1]; arr.push(2, 3, 4); arr.length"),
        JsValue::Number(4.0)
    );
}

#[test]
fn test_array_push_multiple_element_access() {
    // Verify each pushed element is accessible
    assert_eq!(
        eval("const arr: number[] = []; arr.push(1, 2, 3); arr[0]"),
        JsValue::Number(1.0)
    );
    assert_eq!(
        eval("const arr: number[] = []; arr.push(1, 2, 3); arr[1]"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("const arr: number[] = []; arr.push(1, 2, 3); arr[2]"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_push_multiple_sum() {
    // Bug reproduction: push multiple, then sum - was returning NaN
    assert_eq!(
        eval(
            r#"
            const arr: number[] = [];
            arr.push(1, 2, 3);
            let sum: number = 0;
            for (let i = 0; i < arr.length; i++) {
                sum = sum + arr[i];
            }
            sum
        "#
        ),
        JsValue::Number(6.0)
    );
}

#[test]
fn test_array_push_objects_multiple() {
    // Bug reproduction: push multiple objects, access property - was causing NaN
    assert_eq!(
        eval(
            r#"
            interface Node { id: number; edges: Node[]; }
            const n1: Node = { id: 1, edges: [] };
            const n2: Node = { id: 2, edges: [] };
            const n3: Node = { id: 3, edges: [] };
            n1.edges.push(n2, n3);
            n1.edges[0].id + n1.edges[1].id
        "#
        ),
        JsValue::Number(5.0)
    );
}

#[test]
fn test_gc_cycles_test6_minimal() {
    // Minimal reproduction of gc-cycles.ts Test 6 which was returning NaN
    // BUG: The interface declaration is inside the for loop!
    assert_eq!(
        eval(
            r#"
            let sum: number = 0;
            for (let i = 0; i < 1000; i++) {
                interface GraphNode { id: number; edges: GraphNode[]; }

                const n1: GraphNode = { id: 1, edges: [] };
                const n2: GraphNode = { id: 2, edges: [] };
                const n3: GraphNode = { id: 3, edges: [] };
                const n4: GraphNode = { id: 4, edges: [] };
                const n5: GraphNode = { id: 5, edges: [] };

                n1.edges.push(n2, n3);
                n2.edges.push(n1, n3, n4);
                n3.edges.push(n2, n4, n5);
                n4.edges.push(n3, n5);
                n5.edges.push(n4, n1);

                sum = sum + n1.id + n2.id + n3.id + n4.id + n5.id;
            }
            sum
        "#
        ),
        JsValue::Number(15000.0)
    );
}

#[test]
fn test_gc_cycles_test7_minimal() {
    // Minimal reproduction of gc-cycles.ts Test 7 which was returning NaN
    assert_eq!(
        eval(
            r#"
            interface ArrayNode { value: number; refs: ArrayNode[]; }
            let sum: number = 0;
            for (let i = 0; i < 2; i++) {
                const a: ArrayNode = { value: 1, refs: [] };
                const b: ArrayNode = { value: 2, refs: [] };
                const c: ArrayNode = { value: 3, refs: [] };

                a.refs.push(b, c);
                b.refs.push(c, a);
                c.refs.push(a, b);

                sum = sum + a.value + b.value + c.value;
            }
            sum
        "#
        ),
        JsValue::Number(12.0)
    );
}

#[test]
fn test_gc_cycles_all_tests() {
    // Run all gc-cycles tests in sequence to see if one corrupts state for later ones
    // Test 1: 100*(0+1+1+2+...+99+100) = sum(2i+1) for i=0..99 = 10000
    assert_eq!(
        eval(
            r#"
const results: number[] = [];

// Test 1: Two-node cycles
{
    let sum: number = 0;
    for (let i = 0; i < 100; i++) {
        const a: { id: number; other: any } = { id: i, other: null };
        const b: { id: number; other: any } = { id: i + 1, other: null };
        a.other = b;
        b.other = a;
        sum = sum + a.id + b.id;
    }
    results.push(sum);
}

// Test 6: Complex graph with multiple cycles
{
    let sum: number = 0;
    for (let i = 0; i < 100; i++) {
        interface GraphNode { id: number; edges: GraphNode[]; }
        const n1: GraphNode = { id: 1, edges: [] };
        const n2: GraphNode = { id: 2, edges: [] };
        const n3: GraphNode = { id: 3, edges: [] };
        const n4: GraphNode = { id: 4, edges: [] };
        const n5: GraphNode = { id: 5, edges: [] };

        n1.edges.push(n2, n3);
        n2.edges.push(n1, n3, n4);
        n3.edges.push(n2, n4, n5);
        n4.edges.push(n3, n5);
        n5.edges.push(n4, n1);

        sum = sum + n1.id + n2.id + n3.id + n4.id + n5.id;
    }
    results.push(sum);
}

// Test 7: Cycles through arrays
{
    let sum: number = 0;
    for (let i = 0; i < 100; i++) {
        interface ArrayNode { value: number; refs: ArrayNode[]; }
        const a: ArrayNode = { value: 1, refs: [] };
        const b: ArrayNode = { value: 2, refs: [] };
        const c: ArrayNode = { value: 3, refs: [] };

        a.refs.push(b, c);
        b.refs.push(c, a);
        c.refs.push(a, b);

        sum = sum + a.value + b.value + c.value;
    }
    results.push(sum);
}

// Return test 6 result as check (should be 1500)
results[1]
        "#
        ),
        JsValue::Number(1500.0)
    );
}

#[test]
fn test_array_push_element_access() {
    assert_eq!(
        eval("const arr = [1, 2]; arr.push(3); arr[2]"),
        JsValue::Number(3.0)
    );
}

// Array.prototype.pop tests
#[test]
fn test_array_pop_returns_last() {
    assert_eq!(
        eval("const arr = [1, 2, 3]; arr.pop()"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_pop_modifies_length() {
    assert_eq!(
        eval("const arr = [1, 2, 3]; arr.pop(); arr.length"),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_pop_empty() {
    assert_eq!(eval("const arr = []; arr.pop()"), JsValue::Undefined);
}

// Array.prototype.map tests
#[test]
fn test_array_map_double() {
    // [1, 2, 3].map(x => x * 2) should equal [2, 4, 6]
    assert_eq!(
        eval("const arr = [1, 2, 3].map(x => x * 2); arr[0]"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("const arr = [1, 2, 3].map(x => x * 2); arr[1]"),
        JsValue::Number(4.0)
    );
    assert_eq!(
        eval("const arr = [1, 2, 3].map(x => x * 2); arr[2]"),
        JsValue::Number(6.0)
    );
}

#[test]
fn test_array_map_preserves_length() {
    assert_eq!(
        eval("[1, 2, 3].map(x => x * 2).length"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_map_with_index() {
    // map callback receives (element, index, array)
    assert_eq!(
        eval("[10, 20, 30].map((x, i) => i)[1]"),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_map_to_strings() {
    assert_eq!(
        eval("[1, 2, 3].map(x => 'n' + x)[0]"),
        JsValue::String(JsString::from("n1"))
    );
}

// Array.prototype.filter tests
#[test]
fn test_array_filter_evens() {
    assert_eq!(
        eval("[1, 2, 3, 4].filter(x => x % 2 === 0).length"),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_filter_values() {
    assert_eq!(
        eval("[1, 2, 3, 4].filter(x => x % 2 === 0)[0]"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("[1, 2, 3, 4].filter(x => x % 2 === 0)[1]"),
        JsValue::Number(4.0)
    );
}

#[test]
fn test_array_filter_none_match() {
    assert_eq!(
        eval("[1, 2, 3].filter(x => x > 10).length"),
        JsValue::Number(0.0)
    );
}

#[test]
fn test_array_filter_all_match() {
    assert_eq!(
        eval("[1, 2, 3].filter(x => x > 0).length"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_filter_with_index() {
    // Filter elements at even indices
    assert_eq!(
        eval("[10, 20, 30, 40].filter((x, i) => i % 2 === 0).length"),
        JsValue::Number(2.0)
    );
}

// Chaining tests
#[test]
fn test_array_map_filter_chain() {
    // [1, 2, 3, 4].map(x => x * 2).filter(x => x > 4) should be [6, 8]
    assert_eq!(
        eval("[1, 2, 3, 4].map(x => x * 2).filter(x => x > 4).length"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("[1, 2, 3, 4].map(x => x * 2).filter(x => x > 4)[0]"),
        JsValue::Number(6.0)
    );
}

// Array.prototype.forEach tests
#[test]
fn test_array_foreach_side_effect() {
    assert_eq!(
        eval("let sum = 0; [1, 2, 3].forEach(x => sum += x); sum"),
        JsValue::Number(6.0)
    );
}

#[test]
fn test_array_foreach_returns_undefined() {
    assert_eq!(eval("[1, 2, 3].forEach(x => x * 2)"), JsValue::Undefined);
}

#[test]
fn test_array_foreach_with_index() {
    assert_eq!(
        eval("let result = 0; [10, 20, 30].forEach((x, i) => result += i); result"),
        JsValue::Number(3.0)
    );
}

// Array.prototype.reduce tests
#[test]
fn test_array_reduce_sum() {
    assert_eq!(
        eval("[1, 2, 3, 4].reduce((acc, x) => acc + x, 0)"),
        JsValue::Number(10.0)
    );
}

#[test]
fn test_array_reduce_no_initial() {
    // Without initial value, uses first element as initial
    assert_eq!(
        eval("[1, 2, 3, 4].reduce((acc, x) => acc + x)"),
        JsValue::Number(10.0)
    );
}

#[test]
fn test_array_reduce_multiply() {
    assert_eq!(
        eval("[1, 2, 3, 4].reduce((acc, x) => acc * x, 1)"),
        JsValue::Number(24.0)
    );
}

#[test]
fn test_array_reduce_with_index() {
    // Sum of indices
    assert_eq!(
        eval("[10, 20, 30].reduce((acc, x, i) => acc + i, 0)"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_reduce_to_object() {
    assert_eq!(
        eval(
            "const obj = [['a', 1], ['b', 2]].reduce((acc, [k, v]) => { acc[k] = v; return acc; }, {}); obj.a"
        ),
        JsValue::Number(1.0)
    );
}

// Array.prototype.find tests
#[test]
fn test_array_find_found() {
    assert_eq!(eval("[1, 2, 3, 4].find(x => x > 2)"), JsValue::Number(3.0));
}

#[test]
fn test_array_find_not_found() {
    assert_eq!(eval("[1, 2, 3].find(x => x > 10)"), JsValue::Undefined);
}

#[test]
fn test_array_find_with_index() {
    assert_eq!(
        eval("[10, 20, 30].find((x, i) => i === 1)"),
        JsValue::Number(20.0)
    );
}

// Array.prototype.findIndex tests
#[test]
fn test_array_findindex_found() {
    assert_eq!(
        eval("[1, 2, 3, 4].findIndex(x => x > 2)"),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_findindex_not_found() {
    assert_eq!(
        eval("[1, 2, 3].findIndex(x => x > 10)"),
        JsValue::Number(-1.0)
    );
}

#[test]
fn test_array_findindex_first() {
    assert_eq!(
        eval("[5, 10, 15].findIndex(x => x >= 5)"),
        JsValue::Number(0.0)
    );
}

// Array.prototype.indexOf tests
#[test]
fn test_array_indexof_found() {
    assert_eq!(eval("[1, 2, 3, 4].indexOf(3)"), JsValue::Number(2.0));
}

#[test]
fn test_array_indexof_not_found() {
    assert_eq!(eval("[1, 2, 3].indexOf(5)"), JsValue::Number(-1.0));
}

#[test]
fn test_array_indexof_first_occurrence() {
    assert_eq!(eval("[1, 2, 3, 2, 1].indexOf(2)"), JsValue::Number(1.0));
}

#[test]
fn test_array_indexof_from_index() {
    assert_eq!(eval("[1, 2, 3, 2, 1].indexOf(2, 2)"), JsValue::Number(3.0));
}

// Array.prototype.includes tests
#[test]
fn test_array_includes_found() {
    assert_eq!(eval("[1, 2, 3].includes(2)"), JsValue::Boolean(true));
}

#[test]
fn test_array_includes_not_found() {
    assert_eq!(eval("[1, 2, 3].includes(5)"), JsValue::Boolean(false));
}

#[test]
fn test_array_includes_from_index() {
    assert_eq!(eval("[1, 2, 3].includes(1, 1)"), JsValue::Boolean(false));
}

// Array.prototype.slice tests
#[test]
fn test_array_slice_basic() {
    assert_eq!(
        eval("[1, 2, 3, 4, 5].slice(1, 4).length"),
        JsValue::Number(3.0)
    );
    assert_eq!(eval("[1, 2, 3, 4, 5].slice(1, 4)[0]"), JsValue::Number(2.0));
}

#[test]
fn test_array_slice_no_args() {
    assert_eq!(eval("[1, 2, 3].slice().length"), JsValue::Number(3.0));
}

#[test]
fn test_array_slice_negative() {
    assert_eq!(
        eval("[1, 2, 3, 4, 5].slice(-2).length"),
        JsValue::Number(2.0)
    );
    assert_eq!(eval("[1, 2, 3, 4, 5].slice(-2)[0]"), JsValue::Number(4.0));
}

#[test]
fn test_array_slice_start_only() {
    assert_eq!(eval("[1, 2, 3, 4].slice(2).length"), JsValue::Number(2.0));
}

// Array.prototype.concat tests
#[test]
fn test_array_concat_arrays() {
    assert_eq!(eval("[1, 2].concat([3, 4]).length"), JsValue::Number(4.0));
    assert_eq!(eval("[1, 2].concat([3, 4])[2]"), JsValue::Number(3.0));
}

#[test]
fn test_array_concat_values() {
    assert_eq!(eval("[1, 2].concat(3, 4).length"), JsValue::Number(4.0));
}

#[test]
fn test_array_concat_mixed() {
    assert_eq!(
        eval("[1].concat([2, 3], 4, [5]).length"),
        JsValue::Number(5.0)
    );
}

#[test]
fn test_array_concat_is_concat_spreadable_false() {
    // When Symbol.isConcatSpreadable is false, the array should not be spread
    assert_eq!(
        eval(
            r#"
            const arr = [1, 2, 3];
            arr[Symbol.isConcatSpreadable] = false;
            [].concat(arr).length
        "#
        ),
        JsValue::Number(1.0) // arr is treated as a single element, not spread
    );
}

#[test]
fn test_array_concat_is_concat_spreadable_true() {
    // When Symbol.isConcatSpreadable is explicitly true, array-like objects are spread
    assert_eq!(
        eval(
            r#"
            const obj = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true };
            [].concat(obj).length
        "#
        ),
        JsValue::Number(2.0)
    );

    assert_eq!(
        eval(
            r#"
            const obj = { 0: 'a', 1: 'b', length: 2, [Symbol.isConcatSpreadable]: true };
            [].concat(obj)[0]
        "#
        ),
        JsValue::from("a")
    );
}

#[test]
fn test_array_concat_non_array_without_spreadable() {
    // Plain objects without Symbol.isConcatSpreadable are not spread
    assert_eq!(
        eval(
            r#"
            const obj = { 0: 'a', 1: 'b', length: 2 };
            [].concat(obj).length
        "#
        ),
        JsValue::Number(1.0)
    );
}

// Array.prototype.join tests
#[test]
fn test_array_join_default() {
    assert_eq!(
        eval("[1, 2, 3].join()"),
        JsValue::String(JsString::from("1,2,3"))
    );
}

#[test]
fn test_array_join_custom_separator() {
    assert_eq!(
        eval("[1, 2, 3].join('-')"),
        JsValue::String(JsString::from("1-2-3"))
    );
}

#[test]
fn test_array_join_empty() {
    assert_eq!(
        eval("[1, 2, 3].join('')"),
        JsValue::String(JsString::from("123"))
    );
}

// Array.prototype.every tests
#[test]
fn test_array_every_all_pass() {
    assert_eq!(
        eval("[2, 4, 6].every(x => x % 2 === 0)"),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_every_some_fail() {
    assert_eq!(
        eval("[2, 3, 6].every(x => x % 2 === 0)"),
        JsValue::Boolean(false)
    );
}

#[test]
fn test_array_every_empty() {
    assert_eq!(eval("[].every(x => false)"), JsValue::Boolean(true));
}

// Array.prototype.some tests
#[test]
fn test_array_some_one_passes() {
    assert_eq!(eval("[1, 2, 3].some(x => x > 2)"), JsValue::Boolean(true));
}

#[test]
fn test_array_some_none_pass() {
    assert_eq!(eval("[1, 2, 3].some(x => x > 10)"), JsValue::Boolean(false));
}

#[test]
fn test_array_some_empty() {
    assert_eq!(eval("[].some(x => true)"), JsValue::Boolean(false));
}

// Array.prototype.shift tests
#[test]
fn test_array_shift() {
    assert_eq!(eval("let a = [1, 2, 3]; a.shift()"), JsValue::Number(1.0));
    assert_eq!(
        eval("let a = [1, 2, 3]; a.shift(); a.length"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.shift(); a[0]"),
        JsValue::Number(2.0)
    );
    assert_eq!(eval("let a = []; a.shift()"), JsValue::Undefined);
}

// Array.prototype.unshift tests
#[test]
fn test_array_unshift() {
    assert_eq!(
        eval("let a = [1, 2, 3]; a.unshift(0)"),
        JsValue::Number(4.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.unshift(0); a[0]"),
        JsValue::Number(0.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.unshift(-1, 0); a.length"),
        JsValue::Number(5.0)
    );
}

// Array.prototype.reverse tests
#[test]
fn test_array_reverse() {
    assert_eq!(
        eval("let a = [1, 2, 3]; a.reverse(); a[0]"),
        JsValue::Number(3.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.reverse(); a[2]"),
        JsValue::Number(1.0)
    );
}

// Array.prototype.sort tests
#[test]
fn test_array_sort() {
    assert_eq!(
        eval("let a = [3, 1, 2]; a.sort(); a[0]"),
        JsValue::Number(1.0)
    );
    assert_eq!(
        eval("let a = [3, 1, 2]; a.sort(); a[2]"),
        JsValue::Number(3.0)
    );
    assert_eq!(
        eval("let a = ['c', 'a', 'b']; a.sort(); a[0]"),
        JsValue::String(JsString::from("a"))
    );
    // Sort with comparator
    assert_eq!(
        eval("let a = [3, 1, 2]; a.sort((a, b) => b - a); a[0]"),
        JsValue::Number(3.0)
    );
}

// Array.prototype.fill tests
#[test]
fn test_array_fill() {
    assert_eq!(
        eval("let a = [1, 2, 3]; a.fill(0); a[1]"),
        JsValue::Number(0.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.fill(0, 1); a[0]"),
        JsValue::Number(1.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.fill(0, 1); a[1]"),
        JsValue::Number(0.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.fill(0, 1, 2); a[2]"),
        JsValue::Number(3.0)
    );
}

// Array.prototype.copyWithin tests
#[test]
fn test_array_copywithin() {
    assert_eq!(
        eval("let a = [1, 2, 3, 4, 5]; a.copyWithin(0, 3); a[0]"),
        JsValue::Number(4.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3, 4, 5]; a.copyWithin(0, 3); a[1]"),
        JsValue::Number(5.0)
    );
}

// Array.prototype.splice tests
#[test]
fn test_array_splice() {
    assert_eq!(
        eval("let a = [1, 2, 3]; let r = a.splice(1, 1); r[0]"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.splice(1, 1); a.length"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.splice(1, 1, 'a', 'b'); a.length"),
        JsValue::Number(4.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; a.splice(1, 1, 'a', 'b'); a[1]"),
        JsValue::String(JsString::from("a"))
    );
}

// Array.of tests
#[test]
fn test_array_of() {
    assert_eq!(eval("Array.of(1, 2, 3).length"), JsValue::Number(3.0));
    assert_eq!(eval("Array.of(1, 2, 3)[0]"), JsValue::Number(1.0));
    assert_eq!(eval("Array.of(7).length"), JsValue::Number(1.0));
    assert_eq!(eval("Array.of().length"), JsValue::Number(0.0));
}

// Array.from tests
#[test]
fn test_array_from() {
    assert_eq!(eval("Array.from([1, 2, 3]).length"), JsValue::Number(3.0));
    assert_eq!(eval("Array.from([1, 2, 3])[1]"), JsValue::Number(2.0));
    // With map function
    assert_eq!(
        eval("Array.from([1, 2, 3], x => x * 2)[1]"),
        JsValue::Number(4.0)
    );
}

// Array.prototype.at tests
#[test]
fn test_array_at() {
    assert_eq!(eval("[1, 2, 3].at(0)"), JsValue::Number(1.0));
    assert_eq!(eval("[1, 2, 3].at(2)"), JsValue::Number(3.0));
    assert_eq!(eval("[1, 2, 3].at(-1)"), JsValue::Number(3.0));
    assert_eq!(eval("[1, 2, 3].at(-2)"), JsValue::Number(2.0));
    assert_eq!(eval("[1, 2, 3].at(5)"), JsValue::Undefined);
}

#[test]
fn test_array_at_valueof() {
    // Test that valueOf is called on the index argument (ToIntegerOrInfinity)
    assert_eq!(
        eval(
            r#"
            let a = [0, 1, 2, 3];
            let index = { valueOf() { return 1; } };
            a.at(index);
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_at_symbol_throws() {
    // Symbol cannot be converted to number - should throw TypeError
    let result = eval_result("[1, 2, 3].at(Symbol())");
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("TypeError") || err.to_string().contains("Symbol"));
}

#[test]
fn test_array_at_function_length() {
    // Array.prototype.at.length should be 1 (one formal parameter)
    assert_eq!(eval("Array.prototype.at.length"), JsValue::Number(1.0));
}

#[test]
fn test_array_at_function_name() {
    // Array.prototype.at.name should be "at"
    assert_eq!(
        eval("Array.prototype.at.name"),
        JsValue::String(JsString::from("at"))
    );
}

#[test]
fn test_function_call_bind() {
    // Test Function.prototype.call.bind() pattern used by test262 harness
    assert_eq!(
        eval(
            r#"
            var __hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
            __hasOwnProperty({a: 1}, 'a');
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_get_own_property_descriptor_function_length() {
    // Test Object.getOwnPropertyDescriptor on function length property
    assert_eq!(
        eval(
            r#"
            var desc = Object.getOwnPropertyDescriptor(Array.prototype.at, 'length');
            desc.value;
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_function_length_descriptor_attributes() {
    // Test that function.length has correct property descriptor attributes
    // Per spec: writable: false, enumerable: false, configurable: true
    assert_eq!(
        eval(
            r#"
            var desc = Object.getOwnPropertyDescriptor(Array.prototype.at, 'length');
            [desc.writable, desc.enumerable, desc.configurable].join(',');
            "#
        ),
        JsValue::String(JsString::from("false,false,true"))
    );
}

#[test]
fn test_function_name_descriptor_attributes() {
    // Test that function.name has correct property descriptor attributes
    // Per spec: writable: false, enumerable: false, configurable: true
    assert_eq!(
        eval(
            r#"
            var desc = Object.getOwnPropertyDescriptor(Array.prototype.at, 'name');
            [desc.value, desc.writable, desc.enumerable, desc.configurable].join(',');
            "#
        ),
        JsValue::String(JsString::from("at,false,false,true"))
    );
}

#[test]
fn test_verify_property_pattern() {
    // Test the exact pattern used by test262 propertyHelper.js
    assert_eq!(
        eval(
            r#"
            // Capture primordials like propertyHelper.js does
            var __getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
            var __hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);

            // Verify length property like the test does
            var obj = Array.prototype.at;
            var name = "length";
            var originalDesc = __getOwnPropertyDescriptor(obj, name);

            // Return the result
            [
                originalDesc.value,
                originalDesc.writable,
                originalDesc.enumerable,
                originalDesc.configurable
            ].join(',');
            "#
        ),
        JsValue::String(JsString::from("1,false,false,true"))
    );
}

#[test]
fn test_full_verify_property_simulation() {
    // Simulate the full verifyProperty call from test262
    assert_eq!(
        eval(
            r#"
            // From propertyHelper.js
            var __hasOwnProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
            var __getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

            function verifyProperty(obj, name, desc) {
                var originalDesc = __getOwnPropertyDescriptor(obj, name);
                var nameStr = String(name);

                if (!__hasOwnProperty(obj, name)) {
                    throw new Error("obj should have own property " + nameStr);
                }

                if (__hasOwnProperty(desc, 'value')) {
                    if (desc.value !== originalDesc.value) {
                        throw new Error("Expected " + nameStr + " to have value " + desc.value + " but got " + originalDesc.value);
                    }
                }

                return true;
            }

            // The actual test
            verifyProperty(Array.prototype.at, "length", { value: 1 });
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_assert_samevalue_pattern() {
    // Test assert.sameValue pattern from test262
    assert_eq!(
        eval(
            r#"
            // From assert.js
            function assert(mustBeTrue, message) {
                if (mustBeTrue === true) return;
                throw new Error(message || 'Expected true');
            }

            assert._isSameValue = function(a, b) {
                if (a === b) {
                    return a !== 0 || 1 / a === 1 / b;
                }
                return a !== a && b !== b;
            };

            assert.sameValue = function(actual, expected, message) {
                if (assert._isSameValue(actual, expected)) return;
                throw new Error(message || 'Expected same value');
            };

            // Test what the test262 test does
            assert.sameValue(typeof Array.prototype.at, 'function');
            "passed";
            "#
        ),
        JsValue::String(JsString::from("passed"))
    );
}

#[test]
fn test_array_map_call() {
    // Test Array.prototype.map.call pattern used in assert.js
    assert_eq!(
        eval(
            r#"
            var result = Array.prototype.map.call([1, 2, 3], String).join(', ');
            result;
            "#
        ),
        JsValue::String(JsString::from("1, 2, 3"))
    );
}

// Array.prototype.lastIndexOf tests
#[test]
fn test_array_lastindexof() {
    assert_eq!(eval("[1, 2, 3, 2, 1].lastIndexOf(2)"), JsValue::Number(3.0));
    assert_eq!(eval("[1, 2, 3].lastIndexOf(4)"), JsValue::Number(-1.0));
}

// Array.prototype.reduceRight tests
#[test]
fn test_array_reduceright() {
    assert_eq!(
        eval("[1, 2, 3].reduceRight((acc, x) => acc + x, 0)"),
        JsValue::Number(6.0)
    );
    assert_eq!(
        eval("['a', 'b', 'c'].reduceRight((acc, x) => acc + x, '')"),
        JsValue::String(JsString::from("cba"))
    );
}

// Array.prototype.flat tests
#[test]
fn test_array_flat() {
    assert_eq!(eval("[[1, 2], [3, 4]].flat()[0]"), JsValue::Number(1.0));
    assert_eq!(eval("[[1, 2], [3, 4]].flat().length"), JsValue::Number(4.0));
    assert_eq!(eval("[1, [2, [3]]].flat(2).length"), JsValue::Number(3.0));
}

// Array.prototype.flatMap tests
#[test]
fn test_array_flatmap() {
    assert_eq!(
        eval("[1, 2, 3].flatMap(x => [x, x * 2]).length"),
        JsValue::Number(6.0)
    );
    assert_eq!(
        eval("[1, 2, 3].flatMap(x => [x, x * 2])[1]"),
        JsValue::Number(2.0)
    );
}

// Array.prototype.findLast tests
#[test]
fn test_array_findlast() {
    assert_eq!(
        eval("[1, 2, 3, 2].findLast(x => x === 2)"),
        JsValue::Number(2.0)
    );
    assert_eq!(eval("[1, 2, 3].findLast(x => x > 1)"), JsValue::Number(3.0));
    assert_eq!(eval("[1, 2, 3].findLast(x => x > 10)"), JsValue::Undefined);
}

// Array.prototype.findLastIndex tests
#[test]
fn test_array_findlastindex() {
    assert_eq!(
        eval("[1, 2, 3, 2].findLastIndex(x => x === 2)"),
        JsValue::Number(3.0)
    );
    assert_eq!(
        eval("[1, 2, 3].findLastIndex(x => x > 1)"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("[1, 2, 3].findLastIndex(x => x > 10)"),
        JsValue::Number(-1.0)
    );
}

// Array.prototype.toReversed tests
#[test]
fn test_array_toreversed() {
    assert_eq!(
        eval("let a = [1, 2, 3]; let b = a.toReversed(); b[0]"),
        JsValue::Number(3.0)
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; let b = a.toReversed(); a[0]"),
        JsValue::Number(1.0)
    ); // Original unchanged
}

// Array.prototype.toSorted tests
#[test]
fn test_array_tosorted() {
    assert_eq!(
        eval("let a = [3, 1, 2]; let b = a.toSorted(); b[0]"),
        JsValue::Number(1.0)
    );
    assert_eq!(
        eval("let a = [3, 1, 2]; let b = a.toSorted(); a[0]"),
        JsValue::Number(3.0)
    ); // Original unchanged
}

// Array.prototype.toSpliced tests
#[test]
fn test_array_tospliced() {
    assert_eq!(
        eval("[1, 2, 3].toSpliced(1, 1, 'a', 'b')[1]"),
        JsValue::String(JsString::from("a"))
    );
    assert_eq!(
        eval("[1, 2, 3].toSpliced(1, 1, 'a', 'b').length"),
        JsValue::Number(4.0)
    );
}

// Array.prototype.with tests
#[test]
fn test_array_with() {
    assert_eq!(
        eval("[1, 2, 3].with(1, 'x')[1]"),
        JsValue::String(JsString::from("x"))
    );
    assert_eq!(
        eval("let a = [1, 2, 3]; let b = a.with(1, 'x'); a[1]"),
        JsValue::Number(2.0)
    ); // Original unchanged
}

// Array.prototype.keys tests
#[test]
fn test_array_keys() {
    // keys() returns an array of indices
    assert_eq!(
        eval("let arr: string[] = ['a', 'b', 'c']; let keys: number[] = arr.keys(); keys[0]"),
        JsValue::Number(0.0)
    );
    assert_eq!(
        eval("let arr: string[] = ['a', 'b', 'c']; let keys: number[] = arr.keys(); keys[2]"),
        JsValue::Number(2.0)
    );
    assert_eq!(
        eval("([1, 2, 3] as number[]).keys().length"),
        JsValue::Number(3.0)
    );
}

// Array.prototype.values tests
#[test]
fn test_array_values() {
    // values() returns an iterator - use next() to get values
    assert_eq!(
        eval("let arr: string[] = ['a', 'b', 'c']; let iter = arr.values(); iter.next().value"),
        JsValue::String(JsString::from("a"))
    );
    assert_eq!(
        eval("let iter = ([1, 2, 3] as number[]).values(); iter.next(); iter.next().value"),
        JsValue::Number(2.0)
    );
    // Iterator should be exhaustible
    assert_eq!(
        eval("let iter = [42].values(); iter.next(); iter.next().done"),
        JsValue::Boolean(true)
    );
}

// Array.prototype.entries tests
#[test]
fn test_array_entries() {
    // entries() returns an array of [index, value] pairs
    assert_eq!(
        eval("let arr: string[] = ['a', 'b']; let entries = arr.entries(); entries[0][0]"),
        JsValue::Number(0.0)
    );
    assert_eq!(
        eval("let arr: string[] = ['a', 'b']; let entries = arr.entries(); entries[0][1]"),
        JsValue::String(JsString::from("a"))
    );
    assert_eq!(
        eval("let arr: string[] = ['a', 'b']; let entries = arr.entries(); entries[1][0]"),
        JsValue::Number(1.0)
    );
    assert_eq!(
        eval("([1, 2, 3] as number[]).entries().length"),
        JsValue::Number(3.0)
    );
}

// Array holes tests
#[test]
fn test_array_holes_basic() {
    // Holes should be undefined when accessed
    assert_eq!(
        eval("const arr: (number | undefined)[] = [1, , 3]; arr[1]"),
        JsValue::Undefined
    );
}

#[test]
fn test_array_holes_length() {
    // Holes count toward length
    assert_eq!(
        eval("const arr: (number | undefined)[] = [1, , 3]; arr.length"),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_holes_at_start() {
    assert_eq!(
        eval("const arr: (number | undefined)[] = [, 1, 2]; arr[0]"),
        JsValue::Undefined
    );
    assert_eq!(
        eval("const arr: (number | undefined)[] = [, 1, 2]; arr[1]"),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_holes_multiple() {
    assert_eq!(
        eval("const arr: (number | undefined)[] = [, , 3, , 5]; arr.length"),
        JsValue::Number(5.0)
    );
    assert_eq!(
        eval("const arr: (number | undefined)[] = [, , 3, , 5]; arr[2]"),
        JsValue::Number(3.0)
    );
    assert_eq!(
        eval("const arr: (number | undefined)[] = [, , 3, , 5]; arr[3]"),
        JsValue::Undefined
    );
}

#[test]
fn test_array_holes_trailing_comma() {
    // Trailing comma doesn't create a hole
    assert_eq!(
        eval("const arr: number[] = [1, 2, ]; arr.length"),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_reduce_with_object_destructuring() {
    // Reduce with object destructuring in callback
    assert_eq!(
        eval(
            r#"
            const products = [
                { price: 10, stock: 5 },
                { price: 20, stock: 3 },
            ];
            products.reduce((total, { price, stock }) => total + price * stock, 0)
        "#
        ),
        JsValue::Number(110.0)
    );
}

#[test]
fn test_reduce_grouping_pattern() {
    // Common grouping pattern using reduce
    assert_eq!(
        eval(
            r#"
            const products = [
                { id: 1, category: "X" },
                { id: 2, category: "Y" },
                { id: 3, category: "X" },
            ];
            const grouped = products.reduce((groups, product) => {
                const category = product.category;
                if (!groups[category]) {
                    groups[category] = [];
                }
                groups[category].push(product);
                return groups;
            }, {});
            Object.keys(grouped).length
        "#
        ),
        JsValue::Number(2.0)
    );
}

// ═══════════════════════════════════════════════════════════════════════════
// Algorithm tests (complex array operations)
// ═══════════════════════════════════════════════════════════════════════════

#[test]
fn test_array_operations_chain() {
    // Test chained array operations
    assert_eq!(
        eval(
            r#"
            const data: number[] = [1, 2, 3, 4, 5];
            const result = data
                .filter(x => x > 2)
                .map(x => x * 2)
                .reduce((sum, x) => sum + x, 0);
            result
        "#
        ),
        JsValue::Number(24.0) // (3+4+5)*2 = 24
    );
}

#[test]
fn test_quicksort() {
    let result = eval(
        r#"
        function quickSort(arr: number[]): number[] {
            if (arr.length <= 1) return arr;
            const pivot = arr[Math.floor(arr.length / 2)];
            const left = arr.filter((x) => x < pivot);
            const middle = arr.filter((x) => x === pivot);
            const right = arr.filter((x) => x > pivot);
            return [...quickSort(left), ...middle, ...quickSort(right)];
        }
        quickSort([64, 34, 25, 12]).join(",")
    "#,
    );
    assert_eq!(result, JsValue::String("12,25,34,64".into()));
}

#[test]
fn test_array_spread_sort() {
    // Test spreading into array and sorting
    assert_eq!(
        eval(
            r#"
            const arr: number[] = [3, 1, 2];
            const sorted = [...arr].sort((a, b) => a - b);
            sorted.join(",")
        "#
        ),
        JsValue::String("1,2,3".into())
    );
}

#[test]
fn test_debug_array_method_lookup() {
    use super::eval_result;

    // Test 1: Check if map method exists on array
    let result = eval_result("const arr = [1, 2, 3]; typeof arr.map");
    println!("typeof arr.map: {:?}", result);

    // Test 2: Check if push method exists on array
    let result2 = eval_result("const arr = [1, 2, 3]; typeof arr.push");
    println!("typeof arr.push: {:?}", result2);

    // Test 3: Try calling map with a simple function
    let result3 = eval_result("[1, 2, 3].map(function(x) { return x * 2; })");
    println!("map with function: {:?}", result3);

    // Test 4: Try calling map with arrow function
    let result4 = eval_result("[1, 2, 3].map(x => x * 2)");
    println!("map with arrow: {:?}", result4);

    // Test 5: Check what arr.map actually is
    let result5 = eval_result("const arr = [1, 2, 3]; arr.map");
    println!("arr.map value: {:?}", result5);

    // Test 6: Check hasOwnProperty for map
    let result6 = eval_result("const arr = [1, 2, 3]; arr.hasOwnProperty('map')");
    println!("arr.hasOwnProperty('map'): {:?}", result6);

    // Test 7: Check hasOwnProperty for push
    let result7 = eval_result("const arr = [1, 2, 3]; arr.hasOwnProperty('push')");
    println!("arr.hasOwnProperty('push'): {:?}", result7);

    // Test 8: Check Object.keys on array
    let result8 = eval_result("const arr = [1, 2, 3]; Object.keys(arr).length");
    println!("Object.keys(arr).length: {:?}", result8);

    // Test 9: Test with stored reference vs literal
    let result9 = eval_result("const arr = [1, 2, 3]; const m = arr.map; typeof m");
    println!("stored method typeof: {:?}", result9);

    // Test 10: Try calling stored reference
    let result10 = eval_result("const arr = [1, 2, 3]; const m = arr.map; m.call(arr, x => x * 2)");
    println!("m.call(arr, fn): {:?}", result10);

    // Test 11: Check prototype explicitly
    let result11 = eval_result("const arr = [1, 2, 3]; Object.getPrototypeOf(arr) !== null");
    println!("has prototype: {:?}", result11);

    // Test 12: push works via direct call
    let result12 = eval_result("const arr = [1, 2, 3]; arr.push(4)");
    println!("arr.push(4): {:?}", result12);

    // Test 13: Literal array direct method call
    let result13 = eval_result("[1, 2, 3].push(4)");
    println!("[1, 2, 3].push(4): {:?}", result13);

    // Test 14: Literal array direct method call with map
    let result14 = eval_result("[1, 2, 3].push");
    println!("[1, 2, 3].push: {:?}", result14);

    // Test 15: Simplest possible callback
    let result15 = eval_result("const arr = [1]; arr.map(function(x) { return x; })");
    println!("arr.map with simplest callback: {:?}", result15);

    // Assert something to make test visible
    assert!(
        result.is_ok() || result.is_err(),
        "This test is for debugging"
    );
}

// ═══════════════════════════════════════════════════════════════════════════════
// Array methods on array-like objects (Test262 conformance)
// ═══════════════════════════════════════════════════════════════════════════════

#[test]
fn test_array_map_on_array_like() {
    // Array.prototype.map should work on array-like objects
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 10, 1: 20 };
            const result: number[] = Array.prototype.map.call(obj, function(x: number): number { return x * 2; });
            result[0]
            "#
        ),
        JsValue::Number(20.0)
    );
}

#[test]
fn test_array_map_on_array_like_result_length() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 10, 1: 20 };
            const result: number[] = Array.prototype.map.call(obj, function(x: number): number { return x * 2; });
            result.length
            "#
        ),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_filter_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number; 2: number } = { length: 3, 0: 1, 1: 2, 2: 3 };
            const result: number[] = Array.prototype.filter.call(obj, function(x: number): boolean { return x > 1; });
            result.length
            "#
        ),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_foreach_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 10, 1: 20 };
            let sum: number = 0;
            Array.prototype.forEach.call(obj, function(x: number): void { sum += x; });
            sum
            "#
        ),
        JsValue::Number(30.0)
    );
}

#[test]
fn test_array_reduce_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number; 2: number } = { length: 3, 0: 1, 1: 2, 2: 3 };
            Array.prototype.reduce.call(obj, function(acc: number, x: number): number { return acc + x; }, 0)
            "#
        ),
        JsValue::Number(6.0)
    );
}

#[test]
fn test_array_some_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 1, 1: 5 };
            Array.prototype.some.call(obj, function(x: number): boolean { return x > 3; })
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_every_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 1, 1: 2 };
            Array.prototype.every.call(obj, function(x: number): boolean { return x > 0; })
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_find_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number; 2: number } = { length: 3, 0: 1, 1: 5, 2: 10 };
            Array.prototype.find.call(obj, function(x: number): boolean { return x > 3; })
            "#
        ),
        JsValue::Number(5.0)
    );
}

#[test]
fn test_array_indexof_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: string; 1: string; 2: string } = { length: 3, 0: "a", 1: "b", 2: "c" };
            Array.prototype.indexOf.call(obj, "b")
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_includes_on_array_like() {
    assert_eq!(
        eval(
            r#"
            const obj: { length: number; 0: number; 1: number } = { length: 2, 0: 10, 1: 20 };
            Array.prototype.includes.call(obj, 20)
            "#
        ),
        JsValue::Boolean(true)
    );
}

// =============================================================================
// Array-like object tests with ToLength coercion
// =============================================================================
// Per ECMAScript spec, Array methods should work with array-like objects.
// The `length` property is coerced via ToLength, which calls ToNumber first.
// This means objects with valueOf/toString should work.

#[test]
fn test_array_map_on_array_like_with_object_length() {
    // Test262: 15.4.4.19-3-19
    // length property is an object with toString returning a number string
    assert_eq!(
        eval(
            r#"
            function callbackfn(val: number, idx: number, obj: any): boolean {
                return val < 10;
            }
            const obj: any = {
                0: 11,
                1: 9,
                length: {
                    toString: function(): string {
                        return '2';
                    }
                }
            };
            const newArr: boolean[] = Array.prototype.map.call(obj, callbackfn);
            newArr.length
            "#
        ),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_map_on_array_like_with_valueof_length() {
    // length property is an object with valueOf returning a number
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 'a',
                1: 'b',
                2: 'c',
                length: {
                    valueOf: function(): number {
                        return 3;
                    }
                }
            };
            const newArr: string[] = Array.prototype.map.call(obj, (x: string) => x.toUpperCase());
            newArr.length
            "#
        ),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_map_on_array_like_valueof_result() {
    // Verify the actual mapped values
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 'a',
                1: 'b',
                length: { valueOf: () => 2 }
            };
            const arr: string[] = Array.prototype.map.call(obj, (x: string) => x.toUpperCase());
            arr[0] + arr[1]
            "#
        ),
        JsValue::String(JsString::from("AB"))
    );
}

#[test]
fn test_array_filter_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 1,
                1: 2,
                2: 3,
                3: 4,
                length: { toString: () => '4' }
            };
            const arr: number[] = Array.prototype.filter.call(obj, (x: number) => x > 2);
            arr.length
            "#
        ),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_filter_on_array_like_result_values() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 1,
                1: 2,
                2: 3,
                length: { valueOf: () => 3 }
            };
            const arr: number[] = Array.prototype.filter.call(obj, (x: number) => x >= 2);
            arr[0] + arr[1]
            "#
        ),
        JsValue::Number(5.0) // 2 + 3
    );
}

#[test]
fn test_array_foreach_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 10,
                1: 20,
                2: 30,
                length: { toString: () => '3' }
            };
            let sum: number = 0;
            Array.prototype.forEach.call(obj, (x: number) => { sum = sum + x; });
            sum
            "#
        ),
        JsValue::Number(60.0)
    );
}

#[test]
fn test_array_reduce_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 1,
                1: 2,
                2: 3,
                length: { valueOf: () => 3 }
            };
            Array.prototype.reduce.call(obj, (acc: number, x: number) => acc + x, 0)
            "#
        ),
        JsValue::Number(6.0)
    );
}

#[test]
fn test_array_every_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 2,
                1: 4,
                2: 6,
                length: { toString: () => '3' }
            };
            Array.prototype.every.call(obj, (x: number) => x % 2 === 0)
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_some_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 1,
                1: 3,
                2: 5,
                length: { valueOf: () => 3 }
            };
            Array.prototype.some.call(obj, (x: number) => x > 4)
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_find_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 'apple',
                1: 'banana',
                2: 'cherry',
                length: { toString: () => '3' }
            };
            Array.prototype.find.call(obj, (x: string) => x.startsWith('b'))
            "#
        ),
        JsValue::String(JsString::from("banana"))
    );
}

#[test]
fn test_array_findindex_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 10,
                1: 20,
                2: 30,
                length: { valueOf: () => 3 }
            };
            Array.prototype.findIndex.call(obj, (x: number) => x === 20)
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_indexof_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 'x',
                1: 'y',
                2: 'z',
                length: { toString: () => '3' }
            };
            Array.prototype.indexOf.call(obj, 'y')
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_includes_on_array_like_with_object_length() {
    assert_eq!(
        eval(
            r#"
            const obj: any = {
                0: 100,
                1: 200,
                length: { valueOf: () => 2 }
            };
            Array.prototype.includes.call(obj, 200)
            "#
        ),
        JsValue::Boolean(true)
    );
}

#[test]
fn test_array_length_coercion_boolean_true() {
    // Boolean true should coerce to 1
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'first', length: true };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(1.0)
    );
}

#[test]
fn test_array_length_coercion_boolean_false() {
    // Boolean false should coerce to 0
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'first', length: false };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(0.0)
    );
}

#[test]
fn test_array_length_coercion_null() {
    // null should coerce to 0
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'first', length: null };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(0.0)
    );
}

#[test]
fn test_array_length_coercion_undefined() {
    // undefined should coerce to 0 (NaN -> 0)
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'first', length: undefined };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(0.0)
    );
}

#[test]
fn test_array_length_coercion_string_number() {
    // String "3" should coerce to 3
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'a', 1: 'b', 2: 'c', length: '3' };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(3.0)
    );
}

#[test]
fn test_array_length_coercion_float_truncated() {
    // Float 2.9 should be truncated to 2
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'a', 1: 'b', 2: 'c', length: 2.9 };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(2.0)
    );
}

#[test]
fn test_array_length_coercion_negative() {
    // Negative numbers should be clamped to 0
    assert_eq!(
        eval(
            r#"
            const obj: any = { 0: 'a', length: -5 };
            Array.prototype.map.call(obj, (x: string) => x).length
            "#
        ),
        JsValue::Number(0.0)
    );
}