orlando-transducers 0.5.1

High-performance transducers, functional optics, and reactive primitives — with WebAssembly bindings for JavaScript
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
//! WASM-compatible pipeline API for JavaScript interop.
//!
//! This module provides a fluent API for building transducer pipelines
//! that can be called from JavaScript via WASM.

use js_sys::{Array, Function, Object, Reflect};
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use web_sys::console;

/// A pipeline represents a composition of transducers that can be applied to data.
///
/// This is the main API for JavaScript consumers.
///
/// # Examples (in JavaScript)
///
/// ```javascript
/// import { Pipeline } from './pkg/orlando.js';
///
/// const pipeline = new Pipeline()
///   .map(x => x * 2)
///   .filter(x => x > 5)
///   .take(3);
///
/// const result = pipeline.toArray([1, 2, 3, 4, 5, 6]);
/// console.log(result); // [6, 8, 10]
/// ```
#[wasm_bindgen]
pub struct Pipeline {
    operations: Vec<Operation>,
}

/// Internal representation of pipeline operations
#[derive(Clone)]
enum Operation {
    Map(Rc<dyn Fn(JsValue) -> JsValue>),
    Filter(Rc<dyn Fn(&JsValue) -> bool>),
    /// Fused Map + Filter for better performance
    MapFilter {
        map: Rc<dyn Fn(JsValue) -> JsValue>,
        filter: Rc<dyn Fn(&JsValue) -> bool>,
    },
    FlatMap(Rc<dyn Fn(JsValue) -> Vec<JsValue>>),
    Take(usize),
    TakeWhile(Rc<dyn Fn(&JsValue) -> bool>),
    Drop(usize),
    DropWhile(Rc<dyn Fn(&JsValue) -> bool>),
    Tap(Rc<dyn Fn(&JsValue)>),
}

#[wasm_bindgen]
impl Pipeline {
    /// Create a new empty pipeline.
    #[wasm_bindgen(constructor)]
    pub fn new() -> Pipeline {
        Pipeline {
            operations: Vec::new(),
        }
    }

    /// Add a map operation to the pipeline.
    ///
    /// # Arguments
    ///
    /// * `f` - A JavaScript function that transforms each value
    #[wasm_bindgen]
    pub fn map(&self, f: &Function) -> Pipeline {
        let f = f.clone();
        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue {
            let this = JsValue::null();
            f.call1(&this, &val).unwrap_or(JsValue::undefined())
        }) as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Add a filter operation to the pipeline.
    ///
    /// # Arguments
    ///
    /// * `pred` - A JavaScript function that returns true for values to keep
    #[wasm_bindgen]
    pub fn filter(&self, pred: &Function) -> Pipeline {
        let pred = pred.clone();
        let mut ops = self.operations.clone();

        let filter_fn = Rc::new(move |val: &JsValue| -> bool {
            let this = JsValue::null();
            match pred.call1(&this, val) {
                Ok(result) => result.as_bool().unwrap_or(false),
                Err(_) => false,
            }
        }) as Rc<dyn Fn(&JsValue) -> bool>;

        // OPTIMIZATION: Fuse Map + Filter into a single operation
        // This reduces function call overhead and improves cache locality
        if let Some(Operation::Map(map_fn)) = ops.pop() {
            ops.push(Operation::MapFilter {
                map: map_fn,
                filter: filter_fn,
            });
        } else {
            ops.push(Operation::Filter(filter_fn));
        }

        Pipeline { operations: ops }
    }

    /// Add a flatMap operation to the pipeline.
    ///
    /// Maps each value to an array and flattens the results.
    ///
    /// # Arguments
    ///
    /// * `f` - A JavaScript function that returns an array for each value
    #[wasm_bindgen(js_name = flatMap)]
    pub fn flat_map(&self, f: &Function) -> Pipeline {
        let f = f.clone();
        let mut ops = self.operations.clone();

        let flatmap_fn = Rc::new(move |val: JsValue| -> Vec<JsValue> {
            let this = JsValue::null();
            match f.call1(&this, &val) {
                Ok(result) => {
                    // Convert JsValue array to Vec<JsValue>
                    if let Ok(array) = result.dyn_into::<Array>() {
                        (0..array.length()).map(|i| array.get(i)).collect()
                    } else {
                        vec![]
                    }
                }
                Err(_) => vec![],
            }
        }) as Rc<dyn Fn(JsValue) -> Vec<JsValue>>;

        ops.push(Operation::FlatMap(flatmap_fn));
        Pipeline { operations: ops }
    }

    /// Take the first n elements.
    ///
    /// # Arguments
    ///
    /// * `n` - Number of elements to take
    #[wasm_bindgen]
    pub fn take(&self, n: usize) -> Pipeline {
        let mut ops = self.operations.clone();
        ops.push(Operation::Take(n));
        Pipeline { operations: ops }
    }

    /// Take elements while predicate is true.
    ///
    /// # Arguments
    ///
    /// * `pred` - A JavaScript function that returns true to continue taking
    #[wasm_bindgen(js_name = takeWhile)]
    pub fn take_while(&self, pred: &Function) -> Pipeline {
        let pred = pred.clone();
        let mut ops = self.operations.clone();
        ops.push(Operation::TakeWhile(Rc::new(move |val| {
            let this = JsValue::null();
            match pred.call1(&this, val) {
                Ok(result) => result.as_bool().unwrap_or(false),
                Err(_) => false,
            }
        })));
        Pipeline { operations: ops }
    }

    /// Skip the first n elements.
    ///
    /// # Arguments
    ///
    /// * `n` - Number of elements to skip
    #[wasm_bindgen]
    pub fn drop(&self, n: usize) -> Pipeline {
        let mut ops = self.operations.clone();
        ops.push(Operation::Drop(n));
        Pipeline { operations: ops }
    }

    /// Skip elements while predicate is true.
    ///
    /// # Arguments
    ///
    /// * `pred` - A JavaScript function that returns true to continue skipping
    #[wasm_bindgen(js_name = dropWhile)]
    pub fn drop_while(&self, pred: &Function) -> Pipeline {
        let pred = pred.clone();
        let mut ops = self.operations.clone();
        ops.push(Operation::DropWhile(Rc::new(move |val| {
            let this = JsValue::null();
            match pred.call1(&this, val) {
                Ok(result) => result.as_bool().unwrap_or(false),
                Err(_) => false,
            }
        })));
        Pipeline { operations: ops }
    }

    /// Perform side effects without transforming values.
    ///
    /// # Arguments
    ///
    /// * `f` - A JavaScript function to call for each value
    #[wasm_bindgen]
    pub fn tap(&self, f: &Function) -> Pipeline {
        let f = f.clone();
        let mut ops = self.operations.clone();
        ops.push(Operation::Tap(Rc::new(move |val| {
            let this = JsValue::null();
            let _ = f.call1(&this, val);
        })));
        Pipeline { operations: ops }
    }

    /// Extract a property from each object (JavaScript convenience).
    ///
    /// This is cleaner than `.map(x => x.propertyName)` for extracting properties.
    ///
    /// # Arguments
    ///
    /// * `property_name` - The name of the property to extract
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const users = [
    ///   { name: 'Alice', age: 30 },
    ///   { name: 'Bob', age: 25 }
    /// ];
    /// const names = new Pipeline().pluck('name').toArray(users);
    /// // names: ['Alice', 'Bob']
    /// ```
    #[wasm_bindgen]
    pub fn pluck(&self, property_name: &str) -> Pipeline {
        let prop_key = JsValue::from_str(property_name);
        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue {
            // Use Reflect.get to extract the property
            Reflect::get(&val, &prop_key).unwrap_or(JsValue::undefined())
        }) as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Extract multiple properties from each object, creating new objects with only those keys.
    ///
    /// This is equivalent to `.map(x => ({ key1: x.key1, key2: x.key2, ... }))`.
    ///
    /// # Arguments
    ///
    /// * `keys` - A JavaScript array of property name strings to extract
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const users = [
    ///   { id: 1, name: 'Alice', age: 30, email: 'alice@example.com' },
    ///   { id: 2, name: 'Bob', age: 25, email: 'bob@example.com' }
    /// ];
    /// const projected = new Pipeline().project(['id', 'name']).toArray(users);
    /// // [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
    /// ```
    #[wasm_bindgen]
    pub fn project(&self, keys: &JsValue) -> Pipeline {
        let keys_array: Array = keys.clone().dyn_into().unwrap_or_else(|_| Array::new());

        // Pre-extract key strings to avoid repeated conversion
        let key_strings: Vec<JsValue> = (0..keys_array.length())
            .map(|i| keys_array.get(i))
            .collect();

        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue {
            let result = Object::new();
            for key in &key_strings {
                if let Ok(prop_val) = Reflect::get(&val, key) {
                    let _ = Reflect::set(&result, key, &prop_val);
                }
            }
            result.into()
        }) as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Remove all falsy values from the stream.
    ///
    /// Filters out `null`, `undefined`, `false`, `0`, `NaN`, and `''` (empty string).
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const data = [1, null, 'hello', undefined, 0, false, '', 42];
    /// const result = new Pipeline().compact().toArray(data);
    /// // [1, 'hello', 42]
    /// ```
    #[wasm_bindgen]
    pub fn compact(&self) -> Pipeline {
        let mut ops = self.operations.clone();

        let filter_fn = Rc::new(move |val: &JsValue| -> bool {
            val.as_bool() != Some(false)
                && !val.is_null()
                && !val.is_undefined()
                && val.as_f64() != Some(0.0)
                && val.as_string().is_none_or(|s| !s.is_empty())
                && !is_nan(val)
        }) as Rc<dyn Fn(&JsValue) -> bool>;

        ops.push(Operation::Filter(filter_fn));
        Pipeline { operations: ops }
    }

    /// Flatten nested arrays to a given depth.
    ///
    /// Each element in the stream that is an array will be expanded. Nesting
    /// is flattened recursively up to the specified depth.
    ///
    /// # Arguments
    ///
    /// * `depth` - Maximum depth to flatten. Use 1 for a single level of flattening.
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const data = [[1, 2], [3, [4, 5]], [6]];
    /// const result = new Pipeline().flatten(1).toArray(data);
    /// // [1, 2, 3, [4, 5], 6]
    ///
    /// const deep = new Pipeline().flatten(2).toArray(data);
    /// // [1, 2, 3, 4, 5, 6]
    /// ```
    #[wasm_bindgen]
    pub fn flatten(&self, depth: usize) -> Pipeline {
        let mut ops = self.operations.clone();

        let flatmap_fn = Rc::new(move |val: JsValue| -> Vec<JsValue> { flatten_value(val, depth) })
            as Rc<dyn Fn(JsValue) -> Vec<JsValue>>;

        ops.push(Operation::FlatMap(flatmap_fn));
        Pipeline { operations: ops }
    }

    /// Filter objects that match all properties in a spec object.
    ///
    /// Keeps only elements where every key in the spec has a matching value.
    /// Comparison uses strict equality (`===`-like semantics).
    ///
    /// # Arguments
    ///
    /// * `spec` - A JavaScript object whose key-value pairs must all match
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const users = [
    ///   { name: 'Alice', active: true, role: 'admin' },
    ///   { name: 'Bob', active: false, role: 'user' },
    ///   { name: 'Charlie', active: true, role: 'user' }
    /// ];
    ///
    /// const result = new Pipeline()
    ///   .where_matches({ active: true })
    ///   .toArray(users);
    /// // [{ name: 'Alice', ... }, { name: 'Charlie', ... }]
    /// ```
    #[wasm_bindgen(js_name = whereMatches)]
    pub fn where_matches(&self, spec: &JsValue) -> Pipeline {
        let spec_obj = spec.clone();

        // Pre-extract spec keys and values
        let spec_keys = Object::keys(&Object::from(spec_obj.clone()));
        let mut spec_entries: Vec<(JsValue, JsValue)> = Vec::new();
        for i in 0..spec_keys.length() {
            let key = spec_keys.get(i);
            if let Ok(val) = Reflect::get(&spec_obj, &key) {
                spec_entries.push((key, val));
            }
        }

        let mut ops = self.operations.clone();

        let filter_fn = Rc::new(move |val: &JsValue| -> bool {
            for (key, expected) in &spec_entries {
                match Reflect::get(val, key) {
                    Ok(actual) => {
                        if !js_strict_eq(&actual, expected) {
                            return false;
                        }
                    }
                    Err(_) => return false,
                }
            }
            true
        }) as Rc<dyn Fn(&JsValue) -> bool>;

        ops.push(Operation::Filter(filter_fn));
        Pipeline { operations: ops }
    }

    /// Apply a lens to extract the focused value from each element.
    ///
    /// Equivalent to `.map(x => myLens.get(x))` but avoids the JS function call overhead.
    ///
    /// # Arguments
    ///
    /// * `optic` - A JsLens to apply
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const nameLens = lens('name');
    /// const users = [{ name: "Alice" }, { name: "Bob" }];
    /// const names = new Pipeline().viewLens(nameLens).toArray(users);
    /// // names: ["Alice", "Bob"]
    /// ```
    #[wasm_bindgen(js_name = viewLens)]
    pub fn view_lens(&self, optic: &crate::optics_wasm::JsLens) -> Pipeline {
        let get_fn = optic.get_fn.clone();
        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue { get_fn(&val) })
            as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Transform each element's focused value through a lens using a function.
    ///
    /// Equivalent to `.map(x => myLens.over(x, fn))`.
    ///
    /// # Arguments
    ///
    /// * `optic` - A JsLens to apply
    /// * `f` - A JavaScript function to transform the focused value
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const priceLens = lens('price');
    /// const items = [{ name: "A", price: 10 }, { name: "B", price: 20 }];
    /// const discounted = new Pipeline()
    ///   .overLens(priceLens, p => p * 0.9)
    ///   .toArray(items);
    /// // [{ name: "A", price: 9 }, { name: "B", price: 18 }]
    /// ```
    #[wasm_bindgen(js_name = overLens)]
    pub fn over_lens(&self, optic: &crate::optics_wasm::JsLens, f: &Function) -> Pipeline {
        let get_fn = optic.get_fn.clone();
        let set_fn = optic.set_fn.clone();
        let f = f.clone();
        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue {
            let current = get_fn(&val);
            let this = JsValue::null();
            let updated = f.call1(&this, &current).unwrap_or_else(|_| current.clone());
            set_fn(&val, updated)
        }) as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Filter elements based on a predicate applied to the focused value of a lens.
    ///
    /// Equivalent to `.filter(x => pred(myLens.get(x)))`.
    ///
    /// # Arguments
    ///
    /// * `optic` - A JsLens to extract the value to test
    /// * `pred` - A JavaScript predicate function
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const ageLens = lens('age');
    /// const users = [{ name: "Alice", age: 25 }, { name: "Bob", age: 17 }];
    /// const adults = new Pipeline()
    ///   .filterLens(ageLens, a => a >= 18)
    ///   .toArray(users);
    /// // [{ name: "Alice", age: 25 }]
    /// ```
    #[wasm_bindgen(js_name = filterLens)]
    pub fn filter_lens(&self, optic: &crate::optics_wasm::JsLens, pred: &Function) -> Pipeline {
        let get_fn = optic.get_fn.clone();
        let pred = pred.clone();
        let mut ops = self.operations.clone();

        let filter_fn = Rc::new(move |val: &JsValue| -> bool {
            let focused = get_fn(val);
            let this = JsValue::null();
            match pred.call1(&this, &focused) {
                Ok(result) => result.as_bool().unwrap_or(false),
                Err(_) => false,
            }
        }) as Rc<dyn Fn(&JsValue) -> bool>;

        ops.push(Operation::Filter(filter_fn));
        Pipeline { operations: ops }
    }

    /// Set the focused value of a lens on every element.
    ///
    /// Equivalent to `.map(x => myLens.set(x, value))`.
    ///
    /// # Arguments
    ///
    /// * `optic` - A JsLens to apply
    /// * `value` - The value to set
    ///
    /// # Examples (JavaScript)
    ///
    /// ```javascript
    /// const statusLens = lens('status');
    /// const items = [{ id: 1, status: "draft" }, { id: 2, status: "draft" }];
    /// const published = new Pipeline()
    ///   .setLens(statusLens, "published")
    ///   .toArray(items);
    /// // [{ id: 1, status: "published" }, { id: 2, status: "published" }]
    /// ```
    #[wasm_bindgen(js_name = setLens)]
    pub fn set_lens(&self, optic: &crate::optics_wasm::JsLens, value: JsValue) -> Pipeline {
        let set_fn = optic.set_fn.clone();
        let mut ops = self.operations.clone();

        let map_fn = Rc::new(move |val: JsValue| -> JsValue { set_fn(&val, value.clone()) })
            as Rc<dyn Fn(JsValue) -> JsValue>;

        ops.push(Operation::Map(map_fn));
        Pipeline { operations: ops }
    }

    /// Execute the pipeline and collect results into an array.
    ///
    /// # Arguments
    ///
    /// * `source` - JavaScript array to process
    #[wasm_bindgen(js_name = toArray)]
    pub fn to_array(&self, source: &Array) -> Array {
        let result = Array::new();
        let mut should_stop = false;
        let mut state = ProcessState::new();

        for i in 0..source.length() {
            if should_stop {
                break;
            }

            let val = source.get(i);
            let results = self.process_value_with_state(val, &mut state);

            for res in results {
                match res {
                    ProcessResult::Continue(v) => {
                        result.push(&v);
                    }
                    ProcessResult::Skip => {
                        // Skip this value
                    }
                    ProcessResult::Stop(v) => {
                        if let Some(val) = v {
                            result.push(&val);
                        }
                        should_stop = true;
                        break;
                    }
                }
            }
        }

        result
    }

    /// Reduce the source array with a custom reducer function.
    ///
    /// # Arguments
    ///
    /// * `source` - JavaScript array to process
    /// * `reducer` - JavaScript function (acc, val) => acc
    /// * `initial` - Initial accumulator value
    #[wasm_bindgen]
    pub fn reduce(&self, source: &Array, reducer: &Function, initial: JsValue) -> JsValue {
        let mut acc = initial;
        let mut should_stop = false;
        let mut state = ProcessState::new();

        for i in 0..source.length() {
            if should_stop {
                break;
            }

            let val = source.get(i);
            let results = self.process_value_with_state(val, &mut state);

            for res in results {
                match res {
                    ProcessResult::Continue(v) => {
                        let this = JsValue::null();
                        acc = reducer.call2(&this, &acc, &v).unwrap_or(acc);
                    }
                    ProcessResult::Skip => {}
                    ProcessResult::Stop(v) => {
                        if let Some(val) = v {
                            let this = JsValue::null();
                            acc = reducer.call2(&this, &acc, &val).unwrap_or(acc);
                        }
                        should_stop = true;
                        break;
                    }
                }
            }
        }

        acc
    }

    /// Log pipeline execution to console (for debugging).
    #[wasm_bindgen(js_name = logExecution)]
    pub fn log_execution(&self, source: &Array) -> Array {
        console::log_1(&"Pipeline execution:".into());

        let pipeline = self.tap(&Function::new_with_args("x", "console.log('Value:', x)"));

        pipeline.to_array(source)
    }

    // Internal helper to process a single value through the pipeline
    fn process_value_with_state(
        &self,
        val: JsValue,
        state: &mut ProcessState,
    ) -> Vec<ProcessResult> {
        self.process_value_from(val, 0, state)
    }

    // Process a value starting from a specific operation index
    #[allow(unused_assignments)]
    fn process_value_from(
        &self,
        mut val: JsValue,
        start_idx: usize,
        state: &mut ProcessState,
    ) -> Vec<ProcessResult> {
        for (idx, op) in self.operations.iter().enumerate().skip(start_idx) {
            match op {
                Operation::Map(f) => {
                    val = f(val);
                }
                Operation::Filter(pred) => {
                    if !pred(&val) {
                        return vec![ProcessResult::Skip];
                    }
                }
                // OPTIMIZED: Fused Map + Filter in single operation
                // This eliminates one function call and one match arm per element
                Operation::MapFilter { map, filter } => {
                    val = map(val);
                    if !filter(&val) {
                        return vec![ProcessResult::Skip];
                    }
                }
                Operation::FlatMap(f) => {
                    // Expand the value into multiple values
                    let expanded = f(val);
                    let mut results = Vec::new();

                    // Process each expanded value through the remaining operations
                    for expanded_val in expanded {
                        let sub_results = self.process_value_from(expanded_val, idx + 1, state);

                        // Check if we should stop early
                        let should_stop = sub_results
                            .iter()
                            .any(|r| matches!(r, ProcessResult::Stop(_)));

                        results.extend(sub_results);

                        if should_stop {
                            break;
                        }
                    }

                    return results;
                }
                Operation::Take(n) => {
                    state.take_count += 1;
                    if state.take_count > *n {
                        return vec![ProcessResult::Stop(None)];
                    }
                }
                Operation::TakeWhile(pred) => {
                    if !pred(&val) {
                        return vec![ProcessResult::Stop(None)];
                    }
                }
                Operation::Drop(n) => {
                    if state.drop_count < *n {
                        state.drop_count += 1;
                        return vec![ProcessResult::Skip];
                    }
                }
                Operation::DropWhile(pred) => {
                    if !state.dropping && pred(&val) {
                        return vec![ProcessResult::Skip];
                    } else {
                        state.dropping = false;
                    }
                }
                Operation::Tap(f) => {
                    f(&val);
                }
            }
        }

        vec![ProcessResult::Continue(val)]
    }
}

impl Default for Pipeline {
    fn default() -> Self {
        Self::new()
    }
}

enum ProcessResult {
    Continue(JsValue),
    Skip,
    Stop(Option<JsValue>),
}

/// State maintained during pipeline processing
struct ProcessState {
    take_count: usize,
    drop_count: usize,
    dropping: bool,
}

impl ProcessState {
    fn new() -> Self {
        ProcessState {
            take_count: 0,
            drop_count: 0,
            dropping: false,
        }
    }
}

// Export convenience functions

/// Create a new pipeline.
#[wasm_bindgen(js_name = pipeline)]
pub fn create_pipeline() -> Pipeline {
    Pipeline::new()
}

// ============================================================================
// Multi-Input Operations (Phase 2a)
// ============================================================================

/// Merge multiple arrays by interleaving their elements in round-robin fashion.
///
/// Takes elements from each array in turn until all arrays are exhausted.
/// If arrays have different lengths, continues with remaining arrays.
///
/// # JavaScript Example
///
/// ```javascript
/// import { merge } from 'orlando-transducers';
///
/// const a = [1, 2, 3];
/// const b = [4, 5, 6];
/// const result = merge([a, b]);
/// // result: [1, 4, 2, 5, 3, 6]
/// ```
#[wasm_bindgen]
pub fn merge(arrays: Array) -> Array {
    let result = Array::new();

    // Convert JS arrays to iterators
    let mut iters: Vec<_> = (0..arrays.length())
        .map(|i| {
            let arr = arrays
                .get(i)
                .dyn_into::<Array>()
                .unwrap_or_else(|_| Array::new());
            (arr, 0)
        })
        .collect();

    let mut active = true;
    while active {
        active = false;
        for (arr, idx) in &mut iters {
            if *idx < arr.length() {
                result.push(&arr.get(*idx));
                *idx += 1;
                active = true;
            }
        }
    }

    result
}

/// Compute the intersection of two arrays (elements in both A and B).
///
/// Returns elements that appear in both arrays, preserving order from the first array.
/// Duplicates from the first array are included if the element exists in the second.
///
/// # JavaScript Example
///
/// ```javascript
/// import { intersection } from 'orlando-transducers';
///
/// const a = [1, 2, 3, 4];
/// const b = [3, 4, 5, 6];
/// const result = intersection(a, b);
/// // result: [3, 4]
/// ```
#[wasm_bindgen]
pub fn intersection(array_a: &Array, array_b: &Array) -> Array {
    use std::collections::HashSet;

    // Build a set from array B for O(1) lookup
    let mut set_b = HashSet::new();
    for i in 0..array_b.length() {
        let val = array_b.get(i);
        // Use JSON stringification for comparison (works for primitives and objects)
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            set_b.insert(json.as_string().unwrap_or_default());
        }
    }

    let result = Array::new();
    for i in 0..array_a.length() {
        let val = array_a.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            if set_b.contains(&json.as_string().unwrap_or_default()) {
                result.push(&val);
            }
        }
    }

    result
}

/// Compute the difference of two arrays (elements in A but not in B).
///
/// Returns elements from the first array that don't appear in the second,
/// preserving order from the first array.
///
/// # JavaScript Example
///
/// ```javascript
/// import { difference } from 'orlando-transducers';
///
/// const a = [1, 2, 3, 4];
/// const b = [3, 4, 5, 6];
/// const result = difference(a, b);
/// // result: [1, 2]
/// ```
#[wasm_bindgen]
pub fn difference(array_a: &Array, array_b: &Array) -> Array {
    use std::collections::HashSet;

    // Build a set from array B for O(1) lookup
    let mut set_b = HashSet::new();
    for i in 0..array_b.length() {
        let val = array_b.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            set_b.insert(json.as_string().unwrap_or_default());
        }
    }

    let result = Array::new();
    for i in 0..array_a.length() {
        let val = array_a.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            if !set_b.contains(&json.as_string().unwrap_or_default()) {
                result.push(&val);
            }
        }
    }

    result
}

/// Compute the union of two arrays (unique elements from both A and B).
///
/// Returns all unique elements that appear in either array.
/// Order is preserved: all unique elements from A first, then unique elements from B.
///
/// # JavaScript Example
///
/// ```javascript
/// import { union } from 'orlando-transducers';
///
/// const a = [1, 2, 3];
/// const b = [3, 4, 5];
/// const result = union(a, b);
/// // result: [1, 2, 3, 4, 5]
/// ```
#[wasm_bindgen]
pub fn union(array_a: &Array, array_b: &Array) -> Array {
    use std::collections::HashSet;

    let mut seen = HashSet::new();
    let result = Array::new();

    // Add unique elements from A
    for i in 0..array_a.length() {
        let val = array_a.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            if seen.insert(json.as_string().unwrap_or_default()) {
                result.push(&val);
            }
        }
    }

    // Add unique elements from B
    for i in 0..array_b.length() {
        let val = array_b.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            if seen.insert(json.as_string().unwrap_or_default()) {
                result.push(&val);
            }
        }
    }

    result
}

/// Compute the symmetric difference of two arrays (elements in A or B but not both).
///
/// Returns elements that appear in exactly one of the two arrays.
/// Order: unique-to-A elements first, then unique-to-B elements.
///
/// # JavaScript Example
///
/// ```javascript
/// import { symmetricDifference } from 'orlando-transducers';
///
/// const a = [1, 2, 3, 4];
/// const b = [3, 4, 5, 6];
/// const result = symmetricDifference(a, b);
/// // result: [1, 2, 5, 6]
/// ```
#[wasm_bindgen(js_name = symmetricDifference)]
pub fn symmetric_difference(array_a: &Array, array_b: &Array) -> Array {
    use std::collections::HashSet;

    // Build sets from both arrays
    let mut set_a = HashSet::new();
    for i in 0..array_a.length() {
        let val = array_a.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            set_a.insert(json.as_string().unwrap_or_default());
        }
    }

    let mut set_b = HashSet::new();
    for i in 0..array_b.length() {
        let val = array_b.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            set_b.insert(json.as_string().unwrap_or_default());
        }
    }

    let result = Array::new();
    let mut seen = HashSet::new();

    // Elements in A but not B
    for i in 0..array_a.length() {
        let val = array_a.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            let json_str = json.as_string().unwrap_or_default();
            if !set_b.contains(&json_str) && seen.insert(json_str) {
                result.push(&val);
            }
        }
    }

    // Elements in B but not A
    for i in 0..array_b.length() {
        let val = array_b.get(i);
        if let Ok(json) = js_sys::JSON::stringify(&val) {
            let json_str = json.as_string().unwrap_or_default();
            if !set_a.contains(&json_str) && seen.insert(json_str) {
                result.push(&val);
            }
        }
    }

    result
}

// ============================================================================
// Phase 2b: Additional Operations
// ============================================================================

/// Take the last N elements from an array.
///
/// This operation processes the entire array and returns only the last N elements.
/// Unlike `take()`, which stops early, this requires buffering the full result.
///
/// # JavaScript Example
///
/// ```javascript
/// import { takeLast } from 'orlando-transducers';
///
/// const data = [1, 2, 3, 4, 5];
/// const result = takeLast(data, 3);
/// // result: [3, 4, 5]
/// ```
#[wasm_bindgen(js_name = takeLast)]
pub fn take_last(source: &Array, n: u32) -> Array {
    let len = source.length();

    let result = Array::new();

    if n >= len {
        // Return all elements if n is greater than or equal to array length
        for i in 0..len {
            result.push(&source.get(i));
        }
    } else {
        // Return last n elements
        let start = len - n;
        for i in start..len {
            result.push(&source.get(i));
        }
    }

    result
}

/// Drop the last N elements from an array.
///
/// This operation processes the entire array and returns all elements except the last N.
///
/// # JavaScript Example
///
/// ```javascript
/// import { dropLast } from 'orlando-transducers';
///
/// const data = [1, 2, 3, 4, 5];
/// const result = dropLast(data, 2);
/// // result: [1, 2, 3]
/// ```
#[wasm_bindgen(js_name = dropLast)]
pub fn drop_last(source: &Array, n: u32) -> Array {
    let len = source.length();

    let result = Array::new();

    if n >= len {
        // Return empty array if n is greater than or equal to array length
        return result;
    }

    // Return all but last n elements
    let end = len - n;
    for i in 0..end {
        result.push(&source.get(i));
    }

    result
}

/// Create sliding windows of size N over an array.
///
/// Returns an array of arrays, where each sub-array is a window of N consecutive elements.
/// Windows overlap - each window slides by one element.
///
/// # JavaScript Example
///
/// ```javascript
/// import { aperture } from 'orlando-transducers';
///
/// const data = [1, 2, 3, 4, 5];
/// const result = aperture(data, 3);
/// // result: [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
/// ```
#[wasm_bindgen]
pub fn aperture(source: &Array, size: u32) -> Array {
    let len = source.length();
    let result = Array::new();

    if size == 0 || size > len {
        return result;
    }

    // Create sliding windows
    for i in 0..=(len - size) {
        let window = Array::new();
        for j in 0..size {
            window.push(&source.get(i + j));
        }
        result.push(&window);
    }

    result
}

// ============================================================================
// Phase 4: Aggregation & Statistical Operations (JavaScript Bindings)
// ============================================================================

/// Calculate the product of all numbers in an array.
#[wasm_bindgen]
pub fn product(source: &Array) -> f64 {
    let mut result = 1.0;
    for i in 0..source.length() {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            result *= num;
        }
    }
    result
}

/// Calculate the arithmetic mean (average) of numbers in an array.
#[wasm_bindgen]
pub fn mean(source: &Array) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut sum = 0.0;
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            sum += num;
        }
    }

    JsValue::from_f64(sum / (len as f64))
}

/// Find the median (middle value) of numbers in an array.
#[wasm_bindgen]
pub fn median(source: &Array) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut values: Vec<f64> = Vec::new();
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            values.push(num);
        }
    }

    if values.is_empty() {
        return JsValue::undefined();
    }

    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    let mid = values.len() / 2;
    if values.len() % 2 == 1 {
        JsValue::from_f64(values[mid])
    } else {
        JsValue::from_f64((values[mid - 1] + values[mid]) / 2.0)
    }
}

/// Find the minimum value in an array.
#[wasm_bindgen]
pub fn min(source: &Array) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut min_val = f64::INFINITY;
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            if num < min_val {
                min_val = num;
            }
        }
    }

    if min_val == f64::INFINITY {
        JsValue::undefined()
    } else {
        JsValue::from_f64(min_val)
    }
}

/// Find the maximum value in an array.
#[wasm_bindgen]
pub fn max(source: &Array) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut max_val = f64::NEG_INFINITY;
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            if num > max_val {
                max_val = num;
            }
        }
    }

    if max_val == f64::NEG_INFINITY {
        JsValue::undefined()
    } else {
        JsValue::from_f64(max_val)
    }
}

/// Find the element with the minimum value for a given key function.
#[wasm_bindgen(js_name = minBy)]
pub fn min_by(source: &Array, key_fn: &Function) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut min_element = JsValue::undefined();
    let mut min_key = f64::INFINITY;

    let this = JsValue::null();
    for i in 0..len {
        let element = source.get(i);
        if let Ok(key_val) = key_fn.call1(&this, &element) {
            if let Some(key) = key_val.as_f64() {
                if key < min_key {
                    min_key = key;
                    min_element = element;
                }
            }
        }
    }

    min_element
}

/// Find the element with the maximum value for a given key function.
#[wasm_bindgen(js_name = maxBy)]
pub fn max_by(source: &Array, key_fn: &Function) -> JsValue {
    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut max_element = JsValue::undefined();
    let mut max_key = f64::NEG_INFINITY;

    let this = JsValue::null();
    for i in 0..len {
        let element = source.get(i);
        if let Ok(key_val) = key_fn.call1(&this, &element) {
            if let Some(key) = key_val.as_f64() {
                if key > max_key {
                    max_key = key;
                    max_element = element;
                }
            }
        }
    }

    max_element
}

/// Calculate the variance of numbers in an array.
#[wasm_bindgen]
pub fn variance(source: &Array) -> JsValue {
    let len = source.length();
    if len < 2 {
        return JsValue::undefined();
    }

    let mut values: Vec<f64> = Vec::new();
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            values.push(num);
        }
    }

    if values.len() < 2 {
        return JsValue::undefined();
    }

    let n = values.len() as f64;
    let mean_val: f64 = values.iter().sum::<f64>() / n;

    let sum_squared_diff: f64 = values
        .iter()
        .map(|x| {
            let diff = x - mean_val;
            diff * diff
        })
        .sum();

    JsValue::from_f64(sum_squared_diff / (n - 1.0))
}

/// Calculate the standard deviation of numbers in an array.
#[wasm_bindgen(js_name = stdDev)]
pub fn std_dev(source: &Array) -> JsValue {
    match variance(source) {
        v if v.is_undefined() => JsValue::undefined(),
        v => {
            let var_val = v.as_f64().unwrap();
            JsValue::from_f64(var_val.sqrt())
        }
    }
}

/// Calculate a quantile (percentile) value.
#[wasm_bindgen]
pub fn quantile(source: &Array, p: f64) -> JsValue {
    if !(0.0..=1.0).contains(&p) {
        return JsValue::undefined();
    }

    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut values: Vec<f64> = Vec::new();
    for i in 0..len {
        let val = source.get(i);
        if let Some(num) = val.as_f64() {
            values.push(num);
        }
    }

    if values.is_empty() {
        return JsValue::undefined();
    }

    values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

    let n = values.len();
    if n == 1 {
        return JsValue::from_f64(values[0]);
    }

    let index = p * (n - 1) as f64;
    let lower = index.floor() as usize;
    let upper = index.ceil() as usize;

    if lower == upper {
        JsValue::from_f64(values[lower])
    } else {
        let weight = index - lower as f64;
        JsValue::from_f64(values[lower] * (1.0 - weight) + values[upper] * weight)
    }
}

/// Find the mode (most frequent element) in an array.
#[wasm_bindgen]
pub fn mode(source: &Array) -> JsValue {
    use std::collections::HashMap;

    let len = source.length();
    if len == 0 {
        return JsValue::undefined();
    }

    let mut freq_map: HashMap<String, (JsValue, usize)> = HashMap::new();

    for i in 0..len {
        let element = source.get(i);
        let key = format!("{:?}", element);

        freq_map
            .entry(key)
            .and_modify(|(_, count)| *count += 1)
            .or_insert((element.clone(), 1));
    }

    freq_map
        .into_iter()
        .max_by_key(|(_, (_, count))| *count)
        .map(|(_, (value, _))| value)
        .unwrap_or(JsValue::undefined())
}

// ============================================================================
// Phase 5c: Path Operations (JavaScript-specific)
// ============================================================================

/// Access a nested property using a path array.
///
/// Returns undefined if any part of the path doesn't exist.
///
/// # JavaScript Example
///
/// ```javascript
/// import { path } from 'orlando-transducers';
///
/// const user = {
///   profile: {
///     name: 'Alice',
///     address: {
///       city: 'NYC'
///     }
///   }
/// };
///
/// const name = path(user, ['profile', 'name']);
/// // 'Alice'
///
/// const city = path(user, ['profile', 'address', 'city']);
/// // 'NYC'
///
/// const missing = path(user, ['profile', 'age']);
/// // undefined
/// ```
#[wasm_bindgen]
pub fn path(obj: &JsValue, path_array: &Array) -> JsValue {
    let mut current = obj.clone();

    for i in 0..path_array.length() {
        let key = path_array.get(i);

        if let Some(key_str) = key.as_string() {
            match Reflect::get(&current, &JsValue::from_str(&key_str)) {
                Ok(value) => {
                    if value.is_undefined() {
                        return JsValue::undefined();
                    }
                    current = value;
                }
                Err(_) => return JsValue::undefined(),
            }
        } else {
            return JsValue::undefined();
        }
    }

    current
}

/// Access a nested property with a default value.
///
/// Returns the default value if any part of the path doesn't exist.
///
/// # JavaScript Example
///
/// ```javascript
/// import { pathOr } from 'orlando-transducers';
///
/// const user = {
///   profile: {
///     name: 'Alice'
///   }
/// };
///
/// const name = pathOr(user, ['profile', 'name'], 'Anonymous');
/// // 'Alice'
///
/// const age = pathOr(user, ['profile', 'age'], 0);
/// // 0 (default value)
/// ```
#[wasm_bindgen(js_name = pathOr)]
pub fn path_or(obj: &JsValue, path_array: &Array, default: &JsValue) -> JsValue {
    let result = path(obj, path_array);

    if result.is_undefined() {
        default.clone()
    } else {
        result
    }
}

/// Transform nested properties using a transformation object.
///
/// Applies transformation functions to specific paths in an object,
/// returning a new object with the transformations applied.
///
/// # JavaScript Example
///
/// ```javascript
/// import { evolve } from 'orlando-transducers';
///
/// const user = {
///   name: 'alice',
///   age: 25,
///   profile: {
///     bio: 'hello world'
///   }
/// };
///
/// const transformations = {
///   name: (n) => n.toUpperCase(),
///   age: (a) => a + 1,
///   'profile.bio': (b) => b + '!'
/// };
///
/// const evolved = evolve(user, transformations);
/// // {
/// //   name: 'ALICE',
/// //   age: 26,
/// //   profile: { bio: 'hello world!' }
/// // }
/// ```
#[wasm_bindgen]
pub fn evolve(obj: &JsValue, transformations: &JsValue) -> Result<JsValue, JsValue> {
    // Clone the object to avoid mutation
    let json_string = js_sys::JSON::stringify(obj)?;
    let result = js_sys::JSON::parse(&json_string.as_string().unwrap_or_default())?;

    // Get all transformation keys
    let keys = js_sys::Object::keys(&js_sys::Object::from(transformations.clone()));

    for i in 0..keys.length() {
        let key_str = keys.get(i).as_string().unwrap();

        // Get the transformation function
        if let Ok(transform_fn) = Reflect::get(transformations, &JsValue::from_str(&key_str)) {
            if !transform_fn.is_function() {
                continue;
            }

            let func = js_sys::Function::from(transform_fn);

            // Handle nested paths (e.g., "profile.bio")
            if key_str.contains('.') {
                let path_parts: Vec<&str> = key_str.split('.').collect();
                let path_array = Array::new();
                for part in &path_parts {
                    path_array.push(&JsValue::from_str(part));
                }

                // Get the current value at this path
                let current_value = path(&result, &path_array);

                if !current_value.is_undefined() {
                    // Apply transformation
                    let this = JsValue::null();
                    if let Ok(new_value) = func.call1(&this, &current_value) {
                        // Set the new value at the nested path
                        let mut target = result.clone();
                        for (idx, part) in path_parts.iter().enumerate() {
                            if idx == path_parts.len() - 1 {
                                // Last part - set the value
                                let _ = Reflect::set(&target, &JsValue::from_str(part), &new_value);
                            } else {
                                // Navigate deeper
                                if let Ok(next) = Reflect::get(&target, &JsValue::from_str(part)) {
                                    target = next;
                                }
                            }
                        }
                    }
                }
            } else {
                // Simple top-level property
                if let Ok(current_value) = Reflect::get(&result, &JsValue::from_str(&key_str)) {
                    let this = JsValue::null();
                    if let Ok(new_value) = func.call1(&this, &current_value) {
                        let _ = Reflect::set(&result, &JsValue::from_str(&key_str), &new_value);
                    }
                }
            }
        }
    }

    Ok(result)
}

// ============================================================================
// Phase 5a & 5b: Collection Utilities (JavaScript Bindings)
// ============================================================================

/// Sort array elements by a key function.
///
/// # JavaScript Example
///
/// ```javascript
/// import { sortBy } from 'orlando-transducers';
///
/// const users = [
///   { name: 'Alice', age: 30 },
///   { name: 'Bob', age: 25 },
///   { name: 'Charlie', age: 35 }
/// ];
///
/// const sorted = sortBy(users, u => u.age);
/// // [{ name: 'Bob', age: 25 }, ...]
/// ```
#[wasm_bindgen(js_name = sortBy)]
pub fn sort_by(source: &Array, key_fn: &Function) -> Array {
    let len = source.length();
    let mut items: Vec<(JsValue, f64)> = Vec::new();

    let this = JsValue::null();
    for i in 0..len {
        let item = source.get(i);
        if let Ok(key) = key_fn.call1(&this, &item) {
            if let Some(key_num) = key.as_f64() {
                items.push((item, key_num));
            }
        }
    }

    items.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));

    let result = Array::new();
    for (item, _) in items {
        result.push(&item);
    }
    result
}

/// Sort array elements with a custom comparator.
///
/// # JavaScript Example
///
/// ```javascript
/// import { sortWith } from 'orlando-transducers';
///
/// const numbers = [3, 1, 4, 1, 5, 9, 2, 6];
/// const descending = sortWith(numbers, (a, b) => b - a);
/// // [9, 6, 5, 4, 3, 2, 1, 1]
/// ```
#[wasm_bindgen(js_name = sortWith)]
pub fn sort_with(source: &Array, comparator: &Function) -> Array {
    let len = source.length();
    let mut items: Vec<JsValue> = Vec::new();

    for i in 0..len {
        items.push(source.get(i));
    }

    let this = JsValue::null();
    items.sort_by(|a, b| {
        if let Ok(result) = comparator.call2(&this, a, b) {
            if let Some(cmp) = result.as_f64() {
                if cmp < 0.0 {
                    return std::cmp::Ordering::Less;
                } else if cmp > 0.0 {
                    return std::cmp::Ordering::Greater;
                }
            }
        }
        std::cmp::Ordering::Equal
    });

    let result = Array::new();
    for item in items {
        result.push(&item);
    }
    result
}

/// Reverse the order of array elements.
///
/// # JavaScript Example
///
/// ```javascript
/// import { reverse } from 'orlando-transducers';
///
/// const reversed = reverse([1, 2, 3, 4, 5]);
/// // [5, 4, 3, 2, 1]
/// ```
#[wasm_bindgen]
pub fn reverse(source: &Array) -> Array {
    let len = source.length();
    let result = Array::new();

    for i in (0..len).rev() {
        result.push(&source.get(i));
    }

    result
}

/// Generate a range of numbers.
///
/// # JavaScript Example
///
/// ```javascript
/// import { range } from 'orlando-transducers';
///
/// const numbers = range(0, 10, 1);
/// // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
///
/// const evens = range(0, 20, 2);
/// // [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
/// ```
#[wasm_bindgen]
pub fn range(start: i32, end: i32, step: i32) -> Array {
    let result = Array::new();

    if step == 0 {
        return result;
    }

    let mut current = start;
    if step > 0 {
        while current < end {
            result.push(&JsValue::from_f64(current as f64));
            current += step;
        }
    } else {
        while current > end {
            result.push(&JsValue::from_f64(current as f64));
            current += step;
        }
    }

    result
}

/// Repeat a value N times.
///
/// # JavaScript Example
///
/// ```javascript
/// import { repeat } from 'orlando-transducers';
///
/// const zeros = repeat(0, 5);
/// // [0, 0, 0, 0, 0]
///
/// const template = repeat({ status: 'pending' }, 3);
/// // [{ status: 'pending' }, ...]
/// ```
#[wasm_bindgen]
pub fn repeat(value: &JsValue, n: u32) -> Array {
    let result = Array::new();

    for _ in 0..n {
        result.push(value);
    }

    result
}

/// Repeat an array N times.
///
/// # JavaScript Example
///
/// ```javascript
/// import { cycle } from 'orlando-transducers';
///
/// const pattern = cycle([1, 2, 3], 3);
/// // [1, 2, 3, 1, 2, 3, 1, 2, 3]
/// ```
#[wasm_bindgen]
pub fn cycle(source: &Array, n: u32) -> Array {
    let len = source.length();
    let result = Array::new();

    for _ in 0..n {
        for i in 0..len {
            result.push(&source.get(i));
        }
    }

    result
}

/// Generate values by unfolding from a seed.
///
/// # JavaScript Example
///
/// ```javascript
/// import { unfold } from 'orlando-transducers';
///
/// // Generate powers of 2
/// const powers = unfold(1, x => {
///   const next = x * 2;
///   return next <= 1000 ? next : null;
/// }, 20);
/// // [2, 4, 8, 16, 32, 64, 128, 256, 512]
/// ```
#[wasm_bindgen]
pub fn unfold(seed: &JsValue, f: &Function, limit: u32) -> Array {
    let result = Array::new();
    let mut current = seed.clone();
    let this = JsValue::null();

    for _ in 0..limit {
        match f.call1(&this, &current) {
            Ok(next) => {
                if next.is_null() || next.is_undefined() {
                    break;
                }
                result.push(&next);
                current = next;
            }
            Err(_) => break,
        }
    }

    result
}

// ============================================================================
// Internal helpers for Phase 5-JS pipeline methods
// ============================================================================

/// Recursively flatten a JsValue (if it's an array) up to a given depth.
fn flatten_value(val: JsValue, depth: usize) -> Vec<JsValue> {
    if depth == 0 {
        return vec![val];
    }

    match val.dyn_into::<Array>() {
        Ok(array) => {
            let mut result = Vec::new();
            for i in 0..array.length() {
                let item = array.get(i);
                result.extend(flatten_value(item, depth - 1));
            }
            result
        }
        Err(original) => vec![original],
    }
}

/// Check if a JsValue is NaN.
fn is_nan(val: &JsValue) -> bool {
    js_sys::Number::is_nan(val)
}

/// Strict equality comparison for JsValue, mirroring JavaScript `===`.
fn js_strict_eq(a: &JsValue, b: &JsValue) -> bool {
    // wasm_bindgen's == uses Object.is() semantics, which is close to ===
    // but differs for +0/-0 and NaN. For our use case (matching spec values
    // which are typically primitives), this is sufficient.
    a == b
}