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
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
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
# Orlando JavaScript/TypeScript API Documentation

Complete API reference for using Orlando transducers in JavaScript and TypeScript applications.

## Installation

```bash
npm install orlando-transducers
```

Or use directly from a CDN:

```html
<script type="module">
  import init, { Pipeline } from './pkg/orlando.js';
  await init();
  // Use Pipeline...
</script>
```

## Quick Start

```javascript
import init, { Pipeline } from 'orlando-transducers';

// Initialize WASM module
await init();

// Create a pipeline
const pipeline = new Pipeline()
  .map(x => x * 2)
  .filter(x => x > 10)
  .take(5);

// Execute on data
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = pipeline.toArray(data);

console.log(result); // [12, 14, 16, 18, 20]
```

## Core Concepts

### Transducers vs Array Methods

**Traditional approach** (creates intermediate arrays):
```javascript
const result = data
  .map(x => x * 2)        // creates intermediate array
  .filter(x => x > 10)    // creates another intermediate array
  .slice(0, 5);           // final result
```

**Orlando approach** (single pass, no intermediates):
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2)
  .filter(x => x > 10)
  .take(5);

const result = pipeline.toArray(data); // single pass!
```

### Performance Benefits

1. **No intermediate allocations** - Processes data in a single pass
2. **Early termination** - Stops processing as soon as possible
3. **Composable** - Build complex pipelines from simple operations
4. **WASM-powered** - Native performance via WebAssembly

## API Reference

### Pipeline Class

The main entry point for building transducer pipelines.

#### Constructor

```typescript
new Pipeline(): Pipeline
```

Creates a new empty pipeline.

```javascript
const pipeline = new Pipeline();
```

---

### Transformation Methods

All transformation methods return a new `Pipeline` instance, allowing for method chaining.

#### `map(fn)`

Transforms each value using the provided function.

```typescript
map(fn: (value: T) => U): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2)
  .map(x => x + 1);

pipeline.toArray([1, 2, 3]); // [3, 5, 7]
```

**Use cases:**
- Data transformation
- Property extraction
- Type conversion
- Calculations

---

#### `filter(predicate)`

Keeps only values that match the predicate.

```typescript
filter(predicate: (value: T) => boolean): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .filter(x => x % 2 === 0)
  .filter(x => x > 10);

pipeline.toArray([1, 5, 12, 20, 3]); // [12, 20]
```

**Use cases:**
- Filtering data
- Validation
- Conditional inclusion

---

#### `take(n)`

Takes the first `n` elements, then stops processing.

```typescript
take(n: number): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .filter(x => x % 2 === 0)
  .take(3);

// Only processes until 3 evens are found!
pipeline.toArray([1, 2, 3, 4, 5, 6, 7, 8]); // [2, 4, 6]
```

**Use cases:**
- Pagination
- Limiting results
- Top-N queries
- Early termination for performance

**Performance note:** This is where Orlando shines! It stops processing the moment it has enough elements.

---

#### `takeWhile(predicate)`

Takes elements while the predicate is true, then stops.

```typescript
takeWhile(predicate: (value: T) => boolean): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .takeWhile(x => x < 100);

pipeline.toArray([1, 5, 50, 200, 10]); // [1, 5, 50]
```

**Use cases:**
- Taking until a condition
- Reading until delimiter
- Streaming data processing

---

#### `drop(n)`

Skips the first `n` elements.

```typescript
drop(n: number): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .drop(3);

pipeline.toArray([1, 2, 3, 4, 5]); // [4, 5]
```

**Use cases:**
- Pagination (skip)
- Removing headers
- Offset-based queries

---

#### `dropWhile(predicate)`

Skips elements while the predicate is true.

```typescript
dropWhile(predicate: (value: T) => boolean): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .dropWhile(x => x < 10);

pipeline.toArray([1, 5, 12, 20, 3]); // [12, 20, 3]
```

**Use cases:**
- Skipping headers
- Removing prefixes
- Starting from a condition

---

#### `tap(fn)`

Performs side effects without modifying values.

```typescript
tap(fn: (value: T) => void): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .tap(x => console.log('Processing:', x))
  .map(x => x * 2)
  .tap(x => console.log('Result:', x));

pipeline.toArray([1, 2, 3]);
// Logs:
// Processing: 1
// Result: 2
// Processing: 2
// Result: 4
// Processing: 3
// Result: 6
```

**Use cases:**
- Debugging
- Logging
- Analytics
- Progress tracking

---

### Terminal Operations (Collectors)

Terminal operations execute the pipeline and return a result.

#### `toArray(source)`

Collects all results into an array.

```typescript
toArray(source: Array<T>): Array<U>
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2);

const result = pipeline.toArray([1, 2, 3]); // [2, 4, 6]
```

---

#### `reduce(source, reducer, initial)`

Custom reduction with a reducer function.

```typescript
reduce(source: Array<T>, 
       reducer: (acc: A, value: U) => A, 
       initial: A): A
```

**Example:**
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2);

const sum = pipeline.reduce(
  [1, 2, 3, 4],
  (acc, x) => acc + x,
  0
);
console.log(sum); // 20
```

**Use cases:**
- Custom aggregations
- Building objects from arrays
- Complex reductions

---

### Multi-Input Operations

These standalone functions work with multiple arrays. They don't use the Pipeline API.

#### `takeLast(array, n)`

Takes the last N elements from an array.

```typescript
takeLast(source: Array<T>, n: number): Array<T>
```

**Example:**
```javascript
import { takeLast } from 'orlando-transducers';

const result = takeLast([1, 2, 3, 4, 5], 3);
// result: [3, 4, 5]
```

**Use cases:**
- Get recent items (last N logs, events, etc.)
- Tail of a sequence
- "Show more" from end

**Note:** Unlike `take()`, this requires processing the entire array since it needs to know which elements are last.

---

#### `dropLast(array, n)`

Drops the last N elements from an array.

```typescript
dropLast(source: Array<T>, n: number): Array<T>
```

**Example:**
```javascript
import { dropLast } from 'orlando-transducers';

const result = dropLast([1, 2, 3, 4, 5], 2);
// result: [1, 2, 3]
```

**Use cases:**
- Remove trailing elements
- Trim recent history
- Keep all except last N

---

#### `aperture(array, size)`

Creates sliding windows of a given size.

```typescript
aperture(source: Array<T>, size: number): Array<Array<T>>
```

**Example:**
```javascript
import { aperture } from 'orlando-transducers';

const data = [1, 2, 3, 4, 5];
const windows = aperture(data, 3);
// windows: [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
```

**Use cases:**
- Moving averages
- N-gram analysis
- Sliding window algorithms
- Comparing adjacent elements

**Example - Moving average:**
```javascript
const numbers = [10, 20, 30, 40, 50];
const windows = aperture(numbers, 3);
const averages = windows.map(w => w.reduce((a, b) => a + b) / w.length);
// averages: [20, 30, 40]
```

---

#### `merge(arrays)`

Interleaves elements from multiple arrays in round-robin fashion.

```typescript
merge(arrays: Array<Array<T>>): Array<T>
```

**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]
```

**Use cases:**
- Interleaving data streams
- Round-robin scheduling
- Combining event logs chronologically

---

#### `intersection(arrayA, arrayB)`

Returns elements that appear in both arrays.

```typescript
intersection(a: Array<T>, b: Array<T>): Array<T>
```

**Example:**
```javascript
import { intersection } from 'orlando-transducers';

const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];
const common = intersection(a, b);
// common: [3, 4]
```

**Use cases:**
- Finding common elements
- Set operations
- Filtering by membership

---

#### `difference(arrayA, arrayB)`

Returns elements in A that are not in B.

```typescript
difference(a: Array<T>, b: Array<T>): Array<T>
```

**Example:**
```javascript
import { difference } from 'orlando-transducers';

const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];
const uniqueToA = difference(a, b);
// uniqueToA: [1, 2]
```

**Use cases:**
- Finding new/removed items
- Exclusion lists
- Diff operations

---

#### `union(arrayA, arrayB)`

Returns all unique elements from both arrays.

```typescript
union(a: Array<T>, b: Array<T>): Array<T>
```

**Example:**
```javascript
import { union } from 'orlando-transducers';

const a = [1, 2, 3];
const b = [3, 4, 5];
const allUnique = union(a, b);
// allUnique: [1, 2, 3, 4, 5]
```

**Use cases:**
- Combining datasets
- Merging unique items
- Set union

---

#### `symmetricDifference(arrayA, arrayB)`

Returns elements in either array but not both.

```typescript
symmetricDifference(a: Array<T>, b: Array<T>): Array<T>
```

**Example:**
```javascript
import { symmetricDifference } from 'orlando-transducers';

const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];
const unique = symmetricDifference(a, b);
// unique: [1, 2, 5, 6]
```

**Use cases:**
- Finding differences
- XOR operations
- Change detection

---

### Logic Functions (Phase 3)

Predicate combinators for cleaner conditional logic.

#### `both(pred1, pred2)`

Combines two predicates with AND logic.

```typescript
both(p1: (value: T) => boolean, p2: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { both } from 'orlando-transducers';

const isPositive = x => x > 0;
const isEven = x => x % 2 === 0;
const isPositiveEven = both(isPositive, isEven);

const result = [1, 2, 3, 4, -2].filter(isPositiveEven);
// result: [2, 4]
```

---

#### `either(pred1, pred2)`

Combines two predicates with OR logic.

```typescript
either(p1: (value: T) => boolean, p2: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { either } from 'orlando-transducers';

const isSmall = x => x < 10;
const isLarge = x => x > 100;
const isExtreme = either(isSmall, isLarge);

const result = [5, 50, 105].filter(isExtreme);
// result: [5, 105]
```

---

#### `complement(predicate)`

Negates a predicate.

```typescript
complement(pred: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { complement } from 'orlando-transducers';

const isEven = x => x % 2 === 0;
const isOdd = complement(isEven);

const result = [1, 2, 3, 4, 5].filter(isOdd);
// result: [1, 3, 5]
```

---

#### `allPass(predicates)`

Returns true if ALL predicates pass.

```typescript
allPass(predicates: Array<(value: T) => boolean>): (value: T) => boolean
```

**Example:**
```javascript
import { allPass } from 'orlando-transducers';

const isValid = allPass([
  user => user.age >= 18,
  user => user.email.includes('@'),
  user => user.verified
]);

const validUsers = users.filter(isValid);
```

---

#### `anyPass(predicates)`

Returns true if ANY predicate passes.

```typescript
anyPass(predicates: Array<(value: T) => boolean>): (value: T) => boolean
```

**Example:**
```javascript
import { anyPass } from 'orlando-transducers';

const hasDiscount = anyPass([
  user => user.isPremium,
  user => user.isStudent,
  user => user.couponCode
]);

const discountedUsers = users.filter(hasDiscount);
```

---

## Common Patterns

### Pagination

```javascript
function paginate(data, page, pageSize) {
  return new Pipeline()
    .drop(page * pageSize)
    .take(pageSize)
    .toArray(data);
}

const page2 = paginate([1,2,3,4,5,6,7,8,9,10], 1, 3);
// [4, 5, 6]
```

### Data Transformation Pipeline

```javascript
const processUsers = new Pipeline()
  .filter(user => user.active)
  .map(user => ({
    id: user.id,
    name: user.fullName,
    email: user.email.toLowerCase()
  }))
  .filter(user => user.email.endsWith('@company.com'))
  .take(100);

const activeCompanyUsers = processUsers.toArray(users);
```

### Find First Matching

```javascript
const findFirst = new Pipeline()
  .filter(x => x > 100)
  .take(1);

const result = findFirst.toArray(data);
const firstMatch = result[0]; // or undefined
```

### Debugging Pipeline

```javascript
const debugPipeline = new Pipeline()
  .tap(x => console.log('Input:', x))
  .map(x => x * 2)
  .tap(x => console.log('After map:', x))
  .filter(x => x > 10)
  .tap(x => console.log('After filter:', x));
```

### Combining Multiple Operations

```javascript
const complexPipeline = new Pipeline()
  .map(x => x.trim())                    // clean whitespace
  .filter(x => x.length > 0)             // remove empty
  .map(x => x.toLowerCase())             // normalize
  .filter(x => !x.startsWith('#'))       // remove comments
  .map(x => x.split('='))                // parse key=value
  .filter(([k, v]) => k && v)            // validate pairs
  .map(([k, v]) => ({ [k]: v }));        // to objects

const config = complexPipeline.toArray(lines);
```

## TypeScript Support

Orlando automatically generates TypeScript definitions. Import with full type safety:

```typescript
import init, { Pipeline } from 'orlando-transducers';

await init();

interface User {
  id: number;
  name: string;
  email: string;
  active: boolean;
}

interface UserDTO {
  id: number;
  displayName: string;
}

const pipeline = new Pipeline()
  .filter((user: User) => user.active)
  .map((user: User): UserDTO => ({
    id: user.id,
    displayName: user.name
  }))
  .take(10);

const users: User[] = [/* ... */];
const dtos: UserDTO[] = pipeline.toArray(users);
```

## Performance Tips

### 1. Use Early Termination

```javascript
// ❌ Processes all 1 million items
const bad = data
  .map(expensiveOperation)
  .slice(0, 10);

// ✅ Stops after 10 items
const good = new Pipeline()
  .map(expensiveOperation)
  .take(10)
  .toArray(data);
```

### 2. Filter Early

```javascript
// ❌ Maps all items, then filters
const bad = new Pipeline()
  .map(expensiveOperation)
  .filter(x => x.isValid);

// ✅ Filters first, then maps fewer items
const good = new Pipeline()
  .filter(x => x.isValid)
  .map(expensiveOperation);
```

### 3. Reuse Pipelines

```javascript
// Define once
const userProcessor = new Pipeline()
  .filter(user => user.active)
  .map(user => user.email);

// Reuse multiple times
const emails1 = userProcessor.toArray(users1);
const emails2 = userProcessor.toArray(users2);
```

### 4. Avoid Unnecessary Operations

```javascript
// ❌ Multiple passes
const bad = data
  .map(x => x * 2)
  .map(x => x + 1);

// ✅ Single pass
const good = new Pipeline()
  .map(x => (x * 2) + 1)
  .toArray(data);
```

## Browser Compatibility

Orlando uses WebAssembly and works in all modern browsers:

- ✅ Chrome 57+
- ✅ Firefox 52+
- ✅ Safari 11+
- ✅ Edge 16+

For older browsers, include a WASM polyfill.

## Error Handling

```javascript
try {
  await init(); // Initialize WASM
  
  const pipeline = new Pipeline()
    .map(x => {
      if (typeof x !== 'number') {
        throw new Error(`Expected number, got ${typeof x}`);
      }
      return x * 2;
    });
  
  const result = pipeline.toArray(data);
} catch (error) {
  console.error('Pipeline error:', error);
}
```

## Examples Repository

See the `/examples` directory for complete working examples:

- `examples/basic.html` - Basic usage
- `examples/pagination.html` - Pagination example
- `examples/data-processing.html` - Real-world data processing
- `examples/performance.html` - Performance comparison
- `examples/typescript/` - TypeScript examples

## Multi-Input Operations

Orlando provides powerful multi-input operations for combining and comparing arrays. These are standalone functions (not Pipeline methods) that enable hybrid composition patterns.

### `merge(arrays)`

Merges multiple arrays by interleaving their elements in round-robin fashion.

```typescript
merge(arrays: Array<Array<T>>): Array<T>
```

**Example:**
```javascript
import { merge } from 'orlando-transducers';

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [7, 8, 9];

const result = merge([a, b, c]);
// result: [1, 4, 7, 2, 5, 8, 3, 6, 9]
```

**Handles different lengths:**
```javascript
const a = [1, 2];
const b = [3, 4, 5, 6];
const result = merge([a, b]);
// result: [1, 3, 2, 4, 5, 6]
```

**Use cases:**
- Round-robin scheduling
- Interleaving data from multiple sources
- Creating alternating patterns

**Hybrid Composition Example:**
```javascript
// Process each stream differently, then merge
const pipeline1 = new Pipeline().map(x => x * 2);
const pipeline2 = new Pipeline().map(x => x + 10);

const stream1 = pipeline1.toArray([1, 2, 3]);
const stream2 = pipeline2.toArray([1, 2, 3]);

const merged = merge([stream1, stream2]);
// merged: [2, 11, 4, 12, 6, 13]
```

---

### `intersection(arrayA, arrayB)`

Returns elements that appear in both arrays.

```typescript
intersection(arrayA: Array<T>, arrayB: Array<T>): Array<T>
```

**Example:**
```javascript
import { intersection } from 'orlando-transducers';

const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7];

const common = intersection(a, b);
// common: [3, 4, 5]
```

**Preserves order from first array:**
```javascript
const a = [5, 3, 4, 1];
const b = [1, 3, 5];
const result = intersection(a, b);
// result: [5, 3, 1] (order from a)
```

**Use cases:**
- Finding matching records across datasets
- Filtering by membership
- Database-style joins

---

### `difference(arrayA, arrayB)`

Returns elements in the first array but not in the second.

```typescript
difference(arrayA: Array<T>, arrayB: Array<T>): Array<T>
```

**Example:**
```javascript
import { difference } from 'orlando-transducers';

const a = [1, 2, 3, 4, 5];
const b = [3, 4, 5, 6, 7];

const uniqueToA = difference(a, b);
// uniqueToA: [1, 2]
```

**Use cases:**
- Finding new/deleted items
- Exclusion lists
- Data reconciliation

---

### `union(arrayA, arrayB)`

Returns all unique elements from both arrays.

```typescript
union(arrayA: Array<T>, arrayB: Array<T>): Array<T>
```

**Example:**
```javascript
import { union } from 'orlando-transducers';

const a = [1, 2, 3];
const b = [3, 4, 5];

const allUnique = union(a, b);
// allUnique: [1, 2, 3, 4, 5]
```

**Removes duplicates:**
```javascript
const a = [1, 2, 2, 3];
const b = [3, 4, 4, 5];
const result = union(a, b);
// result: [1, 2, 3, 4, 5]
```

**Use cases:**
- Combining datasets without duplicates
- Creating master lists
- Deduplication across sources

---

### `symmetricDifference(arrayA, arrayB)`

Returns elements that appear in exactly one array (not both).

```typescript
symmetricDifference(arrayA: Array<T>, arrayB: Array<T>): Array<T>
```

**Example:**
```javascript
import { symmetricDifference } from 'orlando-transducers';

const a = [1, 2, 3, 4];
const b = [3, 4, 5, 6];

const uniqueToEach = symmetricDifference(a, b);
// uniqueToEach: [1, 2, 5, 6]
```

**No overlap:**
```javascript
const a = [1, 2];
const b = [3, 4];
const result = symmetricDifference(a, b);
// result: [1, 2, 3, 4]
```

**Use cases:**
- Finding changed items
- XOR operations
- Detecting differences between versions

---

## Hybrid Composition Patterns

Combine transducers with multi-input operations for maximum flexibility.

### Pattern 1: Process → Combine

Process streams independently, then combine:

```javascript
const pipeline = new Pipeline()
  .filter(x => x > 0)
  .map(x => x * 2);

const stream1 = pipeline.toArray(data1);
const stream2 = pipeline.toArray(data2);

const combined = intersection(stream1, stream2);
```

### Pattern 2: Combine → Process

Combine first, then process:

```javascript
const merged = merge([data1, data2, data3]);

const pipeline = new Pipeline()
  .filter(x => x % 2 === 0)
  .take(10);

const result = pipeline.toArray(merged);
```

### Real-World Example: Finding Common Active Users

```javascript
// Get active users from both datasets
const activeInA = new Pipeline()
  .filter(user => user.active)
  .map(user => user.id)
  .toArray(usersA);

const activeInB = new Pipeline()
  .filter(user => user.active)
  .map(user => user.id)
  .toArray(usersB);

// Find users active in both systems
const activeInBoth = intersection(activeInA, activeInB);
```

For more patterns and examples, see the [Hybrid Composition Guide](../HYBRID_COMPOSITION.md).

---

## Advanced Collectors

Orlando provides specialized collector functions for complex data analysis and aggregation.

### `frequencies(array)`

Counts occurrences of each element in the array.

```typescript
frequencies(array: Array<T>): Map<T, number>
```

**Example:**
```javascript
import { frequencies } from 'orlando-transducers';

const data = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const counts = frequencies(data);

// counts: Map {
//   'apple' => 3,
//   'banana' => 2,
//   'cherry' => 1
// }
```

**With pipeline:**
```javascript
const pipeline = new Pipeline()
  .filter(word => word.length > 5)
  .map(word => word.toLowerCase());

const words = pipeline.toArray(text.split(' '));
const wordCounts = frequencies(words);
```

**Use cases:**
- Word frequency analysis
- Event counting
- Distribution analysis
- Histogram generation

---

### `partitionBy(array, keyFn)`

Splits array into consecutive groups where keyFn returns the same value.

```typescript
partitionBy<T, K>(array: Array<T>, keyFn: (value: T) => K): Array<Array<T>>
```

**Example:**
```javascript
import { partitionBy } from 'orlando-transducers';

const numbers = [1, 1, 2, 3, 3, 3, 4, 5, 5];
const groups = partitionBy(numbers, x => x);
// groups: [[1, 1], [2], [3, 3, 3], [4], [5, 5]]

const data = [
  { type: 'A', value: 1 },
  { type: 'A', value: 2 },
  { type: 'B', value: 3 },
  { type: 'B', value: 4 }
];
const byType = partitionBy(data, item => item.type);
// byType: [[{type:'A', value:1}, {type:'A', value:2}],
//          [{type:'B', value:3}, {type:'B', value:4}]]
```

**Use cases:**
- Grouping consecutive similar items
- Run-length encoding
- Chunking by property changes
- Log file analysis

---

### `topK(array, k, [compareFn])`

Returns the k largest elements (maintains relative order).

```typescript
topK<T>(array: Array<T>, k: number, compareFn?: (a: T, b: T) => number): Array<T>
```

**Example:**
```javascript
import { topK } from 'orlando-transducers';

const scores = [85, 92, 78, 95, 88, 72, 99, 81];
const topThree = topK(scores, 3);
// topThree: [99, 95, 92]

// Custom comparison
const users = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 88 }
];
const topUsers = topK(users, 2, (a, b) => a.score - b.score);
// topUsers: [{name: 'Bob', score: 92}, {name: 'Charlie', score: 88}]
```

**Use cases:**
- Leaderboards
- Top performers
- High scores
- Best matches

---

### `reservoirSample(array, k)`

Random sampling with uniform probability (reservoir sampling algorithm).

```typescript
reservoirSample<T>(array: Array<T>, k: number): Array<T>
```

**Example:**
```javascript
import { reservoirSample } from 'orlando-transducers';

const largeDataset = Array.from({ length: 10000 }, (_, i) => i);
const sample = reservoirSample(largeDataset, 100);
// sample: 100 randomly selected items with uniform probability
```

**Use cases:**
- Statistical sampling
- Random selection from large datasets
- A/B testing
- Data subset creation

---

### `cartesianProduct(arrayA, arrayB)`

Returns all possible pairs from two arrays.

```typescript
cartesianProduct<T, U>(arrayA: Array<T>, arrayB: Array<U>): Array<[T, U]>
```

**Example:**
```javascript
import { cartesianProduct } from 'orlando-transducers';

const colors = ['red', 'blue'];
const sizes = ['S', 'M', 'L'];

const combinations = cartesianProduct(colors, sizes);
// combinations: [
//   ['red', 'S'], ['red', 'M'], ['red', 'L'],
//   ['blue', 'S'], ['blue', 'M'], ['blue', 'L']
// ]
```

**Use cases:**
- Product variant generation
- Combinatorial analysis
- Test case generation
- Grid coordinates

---

### `zipLongest(arrayA, arrayB, [fillValue])`

Like zip, but continues until the longer array is exhausted, filling missing values.

```typescript
zipLongest<T, U>(arrayA: Array<T>, arrayB: Array<U>, fillValue?: any): Array<[T | any, U | any]>
```

**Example:**
```javascript
import { zipLongest } from 'orlando-transducers';

const a = [1, 2, 3];
const b = ['a', 'b'];

const result = zipLongest(a, b, null);
// result: [[1, 'a'], [2, 'b'], [3, null]]

const result2 = zipLongest(a, b, undefined);
// result2: [[1, 'a'], [2, 'b'], [3, undefined]]
```

**Use cases:**
- Handling arrays of different lengths
- Data alignment
- Missing value handling
- Table formatting

---

## Statistical Operations

Orlando provides efficient statistical analysis operations for numeric data.

### `product(array)`

Multiplies all numbers in an array.

```typescript
product(array: Array<number>): number
```

**Example:**
```javascript
import { product } from 'orlando-transducers';

const numbers = [2, 3, 4];
const result = product(numbers);
// result: 24

const pipeline = new Pipeline().filter(x => x > 0);
const filtered = pipeline.toArray([1, -2, 3, 4]);
const prod = product(filtered);
// prod: 12
```

**Use cases:**
- Mathematical calculations
- Compound growth rates
- Probability calculations

---

### `mean(array)`

Calculates the arithmetic mean (average) of an array.

```typescript
mean(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { mean } from 'orlando-transducers';

const scores = [85, 92, 78, 95, 88];
const average = mean(scores);
// average: 87.6

// Returns undefined for empty arrays
mean([]); // undefined
```

**Use cases:**
- Performance metrics
- Grade calculations
- Statistical analysis

---

### `median(array)`

Finds the median (middle value) of an array.

```typescript
median(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { median } from 'orlando-transducers';

const odd = [1, 3, 5, 7, 9];
median(odd); // 5

const even = [1, 2, 3, 4];
median(even); // 2.5

median([]); // undefined
```

**Use cases:**
- Robust averaging (less affected by outliers)
- Salary distributions
- Performance baselines

---

### `variance(array)`

Calculates the sample variance.

```typescript
variance(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { variance } from 'orlando-transducers';

const data = [2, 4, 6, 8, 10];
const v = variance(data);
// v: 10.0

variance([5]); // undefined (need at least 2 values)
```

**Use cases:**
- Measuring data spread
- Quality control
- Risk assessment

---

### `stdDev(array)`

Calculates the standard deviation (square root of variance).

```typescript
stdDev(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { stdDev } from 'orlando-transducers';

const data = [2, 4, 6, 8, 10];
const sd = stdDev(data);
// sd: 3.16...

// Useful for measuring consistency
const player1Scores = [50, 52, 48, 51, 49];
const player2Scores = [30, 70, 20, 80, 10];
stdDev(player1Scores); // ~1.58 (consistent)
stdDev(player2Scores); // ~27.39 (variable)
```

**Use cases:**
- Data consistency measurement
- Outlier detection
- Statistical analysis

---

### `min(array)` / `max(array)`

Finds the minimum or maximum value.

```typescript
min(array: Array<number>): number | undefined
max(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { min, max } from 'orlando-transducers';

const scores = [85, 92, 78, 95, 88];
min(scores); // 78
max(scores); // 95

min([]); // undefined
```

---

### `minBy(array, keyFn)` / `maxBy(array, keyFn)`

Finds the element with minimum or maximum key value.

```typescript
minBy<T>(array: Array<T>, keyFn: (value: T) => number): T | undefined
maxBy<T>(array: Array<T>, keyFn: (value: T) => number): T | undefined
```

**Example:**
```javascript
import { minBy, maxBy } from 'orlando-transducers';

const users = [
  { name: 'Alice', score: 85 },
  { name: 'Bob', score: 92 },
  { name: 'Charlie', score: 78 }
];

const lowest = minBy(users, u => u.score);
// lowest: { name: 'Charlie', score: 78 }

const highest = maxBy(users, u => u.score);
// highest: { name: 'Bob', score: 92 }
```

**Use cases:**
- Finding extremes in object arrays
- Best/worst performer
- Price comparisons

---

### `quantile(array, p)`

Calculates the p-th quantile (0 ≤ p ≤ 1) using linear interpolation.

```typescript
quantile(array: Array<number>, p: number): number | undefined
```

**Example:**
```javascript
import { quantile } from 'orlando-transducers';

const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

quantile(data, 0.25); // First quartile (Q1): 3.25
quantile(data, 0.5);  // Median (Q2): 5.5
quantile(data, 0.75); // Third quartile (Q3): 7.75
quantile(data, 0.95); // 95th percentile: 9.55

quantile(data, 1.5); // undefined (p out of range)
```

**Use cases:**
- Percentile calculations
- Performance SLAs (p95, p99)
- Outlier detection

---

### `mode(array)`

Finds the most frequently occurring value.

```typescript
mode(array: Array<number>): number | undefined
```

**Example:**
```javascript
import { mode } from 'orlando-transducers';

const data = [1, 2, 2, 3, 3, 3, 4];
mode(data); // 3 (appears most often)

const tie = [1, 1, 2, 2];
mode(tie); // 1 (returns first mode if tied)

mode([]); // undefined
```

**Use cases:**
- Finding common values
- Survey analysis
- Pattern detection

---

## Collection Utilities

Non-streaming utility operations for sorting, reversing, and generating sequences.

### `sortBy(array, keyFn)`

Sorts elements by the result of a key function.

```typescript
sortBy<T, K>(array: Array<T>, keyFn: (value: T) => K): Array<T>
```

**Example:**
```javascript
import { sortBy } from 'orlando-transducers';

const users = [
  { name: 'Charlie', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
];

const byAge = sortBy(users, u => u.age);
// [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 }, { name: 'Bob', age: 35 }]

const byName = sortBy(users, u => u.name);
// [{ name: 'Alice', ... }, { name: 'Bob', ... }, { name: 'Charlie', ... }]
```

**Use cases:**
- Sorting objects by property
- Custom ordering
- Normalized sorting

---

### `sortWith(array, compareFn)`

Sorts with a custom comparator function.

```typescript
sortWith<T>(array: Array<T>, compareFn: (a: T, b: T) => number): Array<T>
```

**Example:**
```javascript
import { sortWith } from 'orlando-transducers';

const numbers = [3, 1, 4, 1, 5];

// Ascending
const asc = sortWith(numbers, (a, b) => a - b);
// [1, 1, 3, 4, 5]

// Descending
const desc = sortWith(numbers, (a, b) => b - a);
// [5, 4, 3, 1, 1]

// Complex comparison
const items = [
  { priority: 1, name: 'b' },
  { priority: 2, name: 'a' },
  { priority: 1, name: 'a' }
];
const sorted = sortWith(items, (a, b) => {
  if (a.priority !== b.priority) return a.priority - b.priority;
  return a.name.localeCompare(b.name);
});
```

**Use cases:**
- Multi-level sorting
- Custom ordering logic
- Complex comparisons

---

### `reverse(array)`

Reverses the order of elements.

```typescript
reverse<T>(array: Array<T>): Array<T>
```

**Example:**
```javascript
import { reverse } from 'orlando-transducers';

const data = [1, 2, 3, 4, 5];
const reversed = reverse(data);
// reversed: [5, 4, 3, 2, 1]

// With pipeline
const pipeline = new Pipeline().filter(x => x % 2 === 0);
const evens = pipeline.toArray([1, 2, 3, 4, 5, 6]);
const reversedEvens = reverse(evens);
// reversedEvens: [6, 4, 2]
```

**Use cases:**
- Reversing order
- Last-to-first processing
- Stack operations

---

### `range(start, end, step)`

Generates a numeric sequence from start to end (exclusive) with a given step.

```typescript
range(start: number, end: number, step: number): Array<number>
```

**Example:**
```javascript
import { range } from 'orlando-transducers';

range(0, 10, 1);    // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 10, 2);    // [0, 2, 4, 6, 8]
range(10, 0, -1);   // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
range(0, 1, 0.1);   // [0, 0.1, 0.2, ..., 0.9]

// Use with pipeline
const pipeline = new Pipeline().filter(x => x % 3 === 0);
const divisibleBy3 = pipeline.toArray(range(0, 30, 1));
// [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
```

**Use cases:**
- Generating sequences
- Loop replacements
- Index generation

---

### `repeat(value, n)`

Repeats a value N times.

```typescript
repeat<T>(value: T, n: number): Array<T>
```

**Example:**
```javascript
import { repeat } from 'orlando-transducers';

repeat(0, 5);           // [0, 0, 0, 0, 0]
repeat('x', 3);         // ['x', 'x', 'x']
repeat([1, 2], 2);      // [[1, 2], [1, 2]]

// Initialize array with default values
const defaultScores = repeat(0, 10);
```

**Use cases:**
- Array initialization
- Padding
- Default values

---

### `cycle(array, n)`

Repeats an entire array N times.

```typescript
cycle<T>(array: Array<T>, n: number): Array<T>
```

**Example:**
```javascript
import { cycle } from 'orlando-transducers';

cycle([1, 2, 3], 2);         // [1, 2, 3, 1, 2, 3]
cycle(['a', 'b'], 3);        // ['a', 'b', 'a', 'b', 'a', 'b']

// Create repeating pattern
const colors = cycle(['red', 'blue', 'green'], 10);
// ['red', 'blue', 'green', 'red', 'blue', 'green', ...]
```

**Use cases:**
- Repeating patterns
- Round-robin scheduling
- Cyclic data

---

### `unfold(seed, fn, limit)`

Generates a sequence by repeatedly applying a function to a seed value.

```typescript
unfold<T>(seed: T, fn: (value: T) => T | undefined, limit: number): Array<T>
```

**Example:**
```javascript
import { unfold } from 'orlando-transducers';

// Fibonacci sequence
const fib = unfold(
  [0, 1],
  ([a, b]) => [b, a + b],
  10
);
// [[0, 1], [1, 1], [1, 2], [2, 3], [3, 5], [5, 8], ...]

// Powers of 2
const powersOf2 = unfold(1, x => x * 2, 8);
// [2, 4, 8, 16, 32, 64, 128, 256]

// Stops when function returns undefined
const countdown = unfold(5, x => x > 0 ? x - 1 : undefined, 10);
// [4, 3, 2, 1, 0]
```

**Use cases:**
- Generating sequences
- Recursive patterns
- Mathematical series

---

## Path Operations (JavaScript-Specific)

Safe navigation and transformation of nested objects.

### `path(obj, pathArray)`

Safely accesses nested properties using a path array.

```typescript
path(obj: Object, pathArray: Array<string>): any
```

**Example:**
```javascript
import { path } from 'orlando-transducers';

const user = {
  profile: {
    contact: {
      email: 'user@example.com'
    }
  }
};

path(user, ['profile', 'contact', 'email']);
// 'user@example.com'

path(user, ['profile', 'contact', 'phone']);
// undefined (safe - doesn't throw)

path(user, ['nonexistent', 'path']);
// undefined
```

**Use cases:**
- Safe property access
- Deep object navigation
- Optional chaining alternative

---

### `pathOr(obj, pathArray, defaultValue)`

Like `path`, but returns a default value if the path doesn't exist.

```typescript
pathOr(obj: Object, pathArray: Array<string>, defaultValue: any): any
```

**Example:**
```javascript
import { pathOr } from 'orlando-transducers';

const config = {
  server: {
    port: 3000
  }
};

pathOr(config, ['server', 'port'], 8080);
// 3000

pathOr(config, ['server', 'host'], 'localhost');
// 'localhost' (default)

pathOr(config, ['database', 'url'], 'mongodb://localhost');
// 'mongodb://localhost' (default)
```

**Use cases:**
- Configuration with defaults
- Fallback values
- Safe data access

---

### `evolve(obj, transformations)`

Applies transformations to nested object properties immutably.

```typescript
evolve(obj: Object, transformations: Object): Object
```

**Example:**
```javascript
import { evolve } from 'orlando-transducers';

const user = {
  name: 'john',
  age: 30,
  contact: {
    email: 'JOHN@EXAMPLE.COM'
  }
};

const normalized = evolve(user, {
  name: (s) => s.toUpperCase(),
  age: (n) => n + 1,
  contact: {
    email: (s) => s.toLowerCase()
  }
});

// normalized: {
//   name: 'JOHN',
//   age: 31,
//   contact: { email: 'john@example.com' }
// }

// Original is unchanged (immutable)
console.log(user.name); // 'john'
```

**Use cases:**
- Data normalization
- Immutable updates
- Nested transformations
- API response formatting

---

## Logic Functions

Orlando provides predicate combinators and conditional transducers for cleaner, more declarative conditional logic in pipelines.

### Predicate Combinators

Predicate combinators allow you to build complex predicates from simple building blocks.

#### `both(pred1, pred2)`

Combines two predicates with AND logic.

```typescript
both<T>(pred1: (value: T) => boolean, pred2: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { both } from 'orlando-transducers';

const isPositive = x => x > 0;
const isEven = x => x % 2 === 0;
const isPositiveEven = both(isPositive, isEven);

const pipeline = new Pipeline()
  .filter(isPositiveEven);

pipeline.toArray([-2, -1, 0, 1, 2, 3, 4]); // [2, 4]
```

**Use cases:**
- Combining multiple conditions
- Complex validation rules
- Multi-criteria filtering

---

#### `either(pred1, pred2)`

Combines two predicates with OR logic.

```typescript
either<T>(pred1: (value: T) => boolean, pred2: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { either } from 'orlando-transducers';

const isSmall = x => x < 10;
const isLarge = x => x > 100;
const isExtreme = either(isSmall, isLarge);

const pipeline = new Pipeline()
  .filter(isExtreme);

pipeline.toArray([5, 50, 150]); // [5, 150]
```

---

#### `complement(predicate)`

Negates a predicate (returns the opposite).

```typescript
complement<T>(pred: (value: T) => boolean): (value: T) => boolean
```

**Example:**
```javascript
import { complement } from 'orlando-transducers';

const isEven = x => x % 2 === 0;
const isOdd = complement(isEven);

const pipeline = new Pipeline()
  .filter(isOdd);

pipeline.toArray([1, 2, 3, 4, 5]); // [1, 3, 5]
```

---

#### `allPass(predicates)`

Returns true only if ALL predicates pass (short-circuits on first false).

```typescript
allPass<T>(predicates: Array<(value: T) => boolean>): (value: T) => boolean
```

**Example:**
```javascript
import { allPass } from 'orlando-transducers';

const validUser = allPass([
  user => user.age >= 18,
  user => user.email.includes('@'),
  user => user.verified === true,
  user => user.active === true
]);

const pipeline = new Pipeline()
  .filter(validUser);

const valid = pipeline.toArray(users);
```

**Use cases:**
- Multi-criteria validation
- Complex rule checking
- Access control
- Data quality checks

---

#### `anyPass(predicates)`

Returns true if ANY predicate passes (short-circuits on first true).

```typescript
anyPass<T>(predicates: Array<(value: T) => boolean>): (value: T) => boolean
```

**Example:**
```javascript
import { anyPass } from 'orlando-transducers';

const isSpecial = anyPass([
  x => x === 0,
  x => x % 10 === 0,
  x => x > 1000
]);

const pipeline = new Pipeline()
  .filter(isSpecial);

pipeline.toArray([0, 5, 50, 1500, 7]); // [0, 50, 1500]
```

---

### Conditional Transducers

Conditional transducers apply transformations based on predicates, allowing you to branch logic within a pipeline.

#### `When(predicate, transform)`

Applies transform only when predicate is true. Otherwise, value passes through unchanged.

**Note:** When is a transducer class that needs to be instantiated and used with collectors.

**Example:**
```javascript
import { When, toArray } from 'orlando-transducers';

const doubleIfPositive = new When(
  x => x > 0,
  x => x * 2
);

const result = toArray(doubleIfPositive, [-1, 2, -3, 4]);
// result: [-1, 4, -3, 8]
```

**Use cases:**
- Conditional normalization
- Selective transformation
- Data correction
- Format conversion

---

#### `Unless(predicate, transform)`

Applies transform only when predicate is false. Inverse of When.

**Example:**
```javascript
import { Unless, toArray } from 'orlando-transducers';

const zeroIfNegative = new Unless(
  x => x > 0,
  _ => 0
);

const result = toArray(zeroIfNegative, [-1, 2, -3, 4]);
// result: [0, 2, 0, 4]
```

---

#### `IfElse(predicate, onTrue, onFalse)`

Branches on condition - applies different transforms based on predicate.

**Example:**
```javascript
import { IfElse, toArray } from 'orlando-transducers';

const normalize = new IfElse(
  x => x >= 0,
  x => x * 2,      // double if positive
  x => x / 2       // halve if negative
);

const result = toArray(normalize, [-4, 3, -6, 5]);
// result: [-2, 6, -3, 10]
```

**Use cases:**
- Two-way data transformation
- A/B processing
- Type-based handling
- Status-dependent logic

---

### Composing Logic Functions

Logic functions compose beautifully for complex conditional logic:

```javascript
import { both, either, complement, allPass, When } from 'orlando-transducers';

// Complex predicate composition
const isPositiveEven = both(x => x > 0, x => x % 2 === 0);
const isNegativeOdd = both(x => x < 0, complement(x => x % 2 === 0));
const isSpecial = either(isPositiveEven, isNegativeOdd);

const pipeline = new Pipeline()
  .filter(isSpecial)
  .map(x => x * 10);

// Nested logic with When
const complexTransform = new When(
  allPass([
    x => x > 0,
    x => x < 100,
    x => x % 2 === 0
  ]),
  x => x * 2
);
```

---

## Functional Lenses (Optics)

Orlando provides functional lenses for clean, composable, immutable updates to nested data structures. Lenses eliminate verbose object spreading and provide a principled way to work with nested data.

### What are Lenses?

A lens is a first-class accessor that focuses on a part of a data structure, enabling immutable get/set/transform operations.

**Traditional approach** (verbose and error-prone):
```javascript
// Deep nested update with spreading
const updateCity = (user, newCity) => ({
  ...user,
  address: {
    ...user.address,
    city: newCity
  }
});
```

**Orlando lenses** (clean and composable):
```javascript
import { lensPath } from 'orlando-transducers';

const cityLens = lensPath(['address', 'city']);
const updated = cityLens.set(user, newCity);
```

### Why Lenses?

1. **No nested spreading** - Clean syntax for deep updates
2. **Composable** - Build complex accessors from simple ones
3. **Type-safe** - Optional lenses for nullable fields
4. **Streaming** - Combine with transducers for bounded-memory processing

---

### Creating Lenses

#### `lens(property)`

Creates a lens focusing on a single property.

```typescript
lens(property: string): JsLens
```

**Example:**
```javascript
import { lens } from 'orlando-transducers';

const user = { name: 'Alice', age: 30 };

const nameLens = lens('name');
console.log(nameLens.get(user));           // 'Alice'

const updated = nameLens.set(user, 'Bob');
console.log(updated.name);                 // 'Bob'
console.log(user.name);                    // 'Alice' (original unchanged)
```

**Use cases:**
- Simple property access
- Single-level immutable updates
- Building blocks for composition

---

#### `lensPath(path)`

Creates a lens focusing on a deep nested property via an array path.

```typescript
lensPath(path: Array<string>): JsLens
```

**Example:**
```javascript
import { lensPath } from 'orlando-transducers';

const user = {
  name: 'Alice',
  address: {
    city: 'NYC',
    zip: '10001'
  }
};

const cityLens = lensPath(['address', 'city']);
console.log(cityLens.get(user));          // 'NYC'

const updated = cityLens.set(user, 'LA');
console.log(updated.address.city);         // 'LA'
console.log(user.address.city);            // 'NYC' (original unchanged)
```

**Use cases:**
- Deep nested updates
- Avoiding manual composition
- Clean multi-level access

---

#### `optional(property)`

Creates an optional lens for properties that may not exist.

```typescript
optional(property: string): JsOptional
```

**Example:**
```javascript
import { optional } from 'orlando-transducers';

const addressLens = optional('address');

const user1 = { name: 'Alice', address: { city: 'NYC' } };
const user2 = { name: 'Bob' };

console.log(addressLens.get(user1));       // { city: 'NYC' }
console.log(addressLens.get(user2));       // undefined

// over is a no-op when value doesn't exist
const updated = addressLens.over(user2, addr => ({ ...addr, city: 'LA' }));
console.log(updated);                      // { name: 'Bob' } (unchanged)
```

**Use cases:**
- Nullable fields
- Safe optional access
- Conditional updates
- Configuration with optional fields

---

### Lens Methods

All lenses (created with `lens()` or `lensPath()`) support these methods:

#### `get(source)`

Extracts the focused value from the source object.

```typescript
get(source: Object): any
```

**Example:**
```javascript
const nameLens = lens('name');
const user = { name: 'Alice', age: 30 };
console.log(nameLens.get(user)); // 'Alice'
```

---

#### `set(source, value)`

Updates the focused value immutably, returning a new object.

```typescript
set(source: Object, value: any): Object
```

**Example:**
```javascript
const nameLens = lens('name');
const user = { name: 'Alice', age: 30 };
const updated = nameLens.set(user, 'Bob');
// updated: { name: 'Bob', age: 30 }
// user is unchanged
```

**Important:** This returns a **new object**. The original is never modified.

---

#### `over(source, fn)`

Transforms the focused value by applying a function.

```typescript
over(source: Object, fn: (value: any) => any): Object
```

**Example:**
```javascript
const ageLens = lens('age');
const user = { name: 'Alice', age: 30 };

const older = ageLens.over(user, age => age + 1);
// older: { name: 'Alice', age: 31 }

const nameLens = lens('name');
const upper = nameLens.over(user, name => name.toUpperCase());
// upper: { name: 'ALICE', age: 30 }
```

**Use cases:**
- Incrementing counters
- String transformations
- Mathematical operations
- Any computed update

---

#### `compose(otherLens)`

Composes two lenses to focus deeper into nested structures.

```typescript
compose(otherLens: JsLens): JsLens
```

**Example:**
```javascript
const addressLens = lens('address');
const cityLens = lens('city');
const fullLens = addressLens.compose(cityLens);

const user = {
  name: 'Alice',
  address: { city: 'NYC', zip: '10001' }
};

console.log(fullLens.get(user));          // 'NYC'
const updated = fullLens.set(user, 'LA');
console.log(updated.address.city);         // 'LA'
```

**Composition is associative:**
```javascript
// These are equivalent
lensPath(['a', 'b', 'c'])
lens('a').compose(lens('b')).compose(lens('c'))
```

---

### Optional Methods

Optionals (created with `optional()`) support these methods:

#### `get(source)`

Extracts the focused value, returning `undefined` if it doesn't exist.

```typescript
get(source: Object): any | undefined
```

**Example:**
```javascript
const addressLens = optional('address');

const user1 = { name: 'Alice', address: { city: 'NYC' } };
const user2 = { name: 'Bob' };

console.log(addressLens.get(user1));  // { city: 'NYC' }
console.log(addressLens.get(user2));  // undefined
```

---

#### `getOr(source, default)`

Extracts the focused value with a fallback default.

```typescript
getOr(source: Object, default: any): any
```

**Example:**
```javascript
const addressLens = optional('address');

const user = { name: 'Bob' };
const addr = addressLens.getOr(user, { city: 'Unknown', zip: '00000' });
// addr: { city: 'Unknown', zip: '00000' }
```

**Use cases:**
- Configuration with defaults
- Safe data access
- Fallback values

---

#### `set(source, value)`

Updates the focused value immutably (creates the property if it doesn't exist).

```typescript
set(source: Object, value: any): Object
```

**Example:**
```javascript
const phoneLens = optional('phone');

const user = { name: 'Alice' };
const updated = phoneLens.set(user, '555-1234');
// updated: { name: 'Alice', phone: '555-1234' }
```

---

#### `over(source, fn)`

Transforms the focused value only if it exists. Returns source unchanged if value is missing.

```typescript
over(source: Object, fn: (value: any) => any): Object
```

**Example:**
```javascript
const discountLens = optional('discount');

const item1 = { price: 100, discount: 10 };
const item2 = { price: 100 };

const doubled1 = discountLens.over(item1, d => d * 2);
// doubled1: { price: 100, discount: 20 }

const doubled2 = discountLens.over(item2, d => d * 2);
// doubled2: { price: 100 } (unchanged - no discount to transform)
```

---

### React State Management Example

Lenses are perfect for React state updates:

```javascript
import { useState } from 'react';
import { lens, lensPath } from 'orlando-transducers';

function UserProfile() {
  const [user, setUser] = useState({
    name: 'Alice',
    email: 'alice@example.com',
    preferences: {
      theme: 'dark',
      notifications: true
    }
  });

  const nameLens = lens('name');
  const themeLens = lensPath(['preferences', 'theme']);

  const updateName = (newName) => {
    setUser(nameLens.set(user, newName));
  };

  const toggleTheme = () => {
    setUser(themeLens.over(user, theme =>
      theme === 'dark' ? 'light' : 'dark'
    ));
  };

  return (
    <div>
      <input
        value={user.name}
        onChange={(e) => updateName(e.target.value)}
      />
      <button onClick={toggleTheme}>
        Theme: {user.preferences.theme}
      </button>
    </div>
  );
}
```

**Benefits:**
- No nested spreading
- Type-safe with TypeScript
- Reusable lens definitions
- Clear, declarative intent

---

### Shopping Cart Example

Complex state management made simple:

```javascript
import { useState } from 'react';
import { lens, optional } from 'orlando-transducers';

function ShoppingCart() {
  const [cart, setCart] = useState({
    items: [
      { id: 1, name: 'Widget', quantity: 2, price: 10 },
      { id: 2, name: 'Gadget', quantity: 1, price: 20 }
    ],
    discount: null
  });

  const itemsLens = lens('items');
  const discountLens = optional('discount');

  const updateQuantity = (itemId, newQuantity) => {
    const updated = cart.items.map(item =>
      item.id === itemId
        ? lens('quantity').set(item, newQuantity)
        : item
    );
    setCart(itemsLens.set(cart, updated));
  };

  const applyDiscount = (discountCode) => {
    setCart(discountLens.set(cart, { code: discountCode, percent: 10 }));
  };

  const total = cart.items.reduce((sum, item) =>
    sum + (item.price * item.quantity), 0
  );

  const discountAmount = discountLens.get(cart)
    ? total * (cart.discount.percent / 100)
    : 0;

  return (
    <div>
      {cart.items.map(item => (
        <div key={item.id}>
          {item.name} × {item.quantity}
          <button onClick={() => updateQuantity(item.id, item.quantity + 1)}>
            +
          </button>
        </div>
      ))}
      <p>Subtotal: ${total}</p>
      {discountAmount > 0 && <p>Discount: -${discountAmount}</p>}
      <p>Total: ${total - discountAmount}</p>
    </div>
  );
}
```

---

### Streaming Lenses: The Killer Feature ⚡

**Orlando is the first lens library to integrate with transducers** for streaming data processing with lenses.

#### Traditional Approach (Multiple Passes)

```javascript
// 1. Extract nested values (full array iteration)
const cities = users.map(user => user.address.city);

// 2. Filter (full array iteration)
const nyCities = cities.filter(city => city === 'NYC');

// 3. Unique (full array iteration)
const unique = [...new Set(nyCities)];

// Result: 3 full passes through data
```

#### Orlando Streaming Lenses (Single Pass)

```javascript
import { lens, Pipeline } from 'orlando-transducers';

const cityLens = lensPath(['address', 'city']);

const unique = new Pipeline()
  .map(user => cityLens.get(user))     // Extract with lens
  .filter(city => city === 'NYC')       // Filter
  .unique()                              // Deduplicate
  .toArray(users);                       // Single pass!
```

**Benefits:**
- Single pass through data
- No intermediate arrays
- Bounded memory usage
- Early termination support
- WASM performance

#### Bulk Updates with Lenses + Transducers

```javascript
import { lens, Pipeline } from 'orlando-transducers';

const users = [
  { name: 'alice', email: 'ALICE@EXAMPLE.COM', age: 30 },
  { name: 'bob', email: 'BOB@EXAMPLE.COM', age: 25 }
];

const nameLens = lens('name');
const emailLens = lens('email');
const ageLens = lens('age');

// Normalize all users in a single pass
const normalized = new Pipeline()
  .map(user => nameLens.over(user, name => name.toUpperCase()))
  .map(user => emailLens.over(user, email => email.toLowerCase()))
  .map(user => ageLens.over(user, age => age + 1))
  .toArray(users);

// Result: [
//   { name: 'ALICE', email: 'alice@example.com', age: 31 },
//   { name: 'BOB', email: 'bob@example.com', age: 26 }
// ]
```

---

### Lens Laws

Orlando lenses satisfy three mathematical laws guaranteeing correctness:

#### 1. GetPut Law
```javascript
// Setting what you get doesn't change the object
const l = lens('name');
const obj = { name: 'Alice' };
l.set(obj, l.get(obj)) === obj  // ✓ true (structurally)
```

#### 2. PutGet Law
```javascript
// Getting what you just set returns that value
const l = lens('name');
const obj = { name: 'Alice' };
l.get(l.set(obj, 'Bob')) === 'Bob'  // ✓ true
```

#### 3. PutPut Law
```javascript
// Second set wins
const l = lens('name');
const obj = { name: 'Alice' };
l.set(l.set(obj, 'Bob'), 'Charlie') === l.set(obj, 'Charlie')  // ✓ true (structurally)
```

These laws are automatically verified via property-based tests in Orlando's test suite.

---

### TypeScript Support

Lenses work seamlessly with TypeScript:

```typescript
import { lens, lensPath, optional } from 'orlando-transducers';

interface User {
  name: string;
  age: number;
  address?: {
    city: string;
    zip: string;
  };
}

const user: User = {
  name: 'Alice',
  age: 30,
  address: { city: 'NYC', zip: '10001' }
};

const nameLens = lens('name');
const cityLens = lensPath(['address', 'city']);
const addressLens = optional('address');

const updated: User = nameLens.set(user, 'Bob');
const city: any = cityLens.get(user);
const addr: any = addressLens.getOr(user, { city: 'Unknown', zip: '00000' });
```

---

### Performance Tips

1. **Create lenses once, reuse them:**
   ```javascript
   // Good - create once
   const nameLens = lens('name');
   const updateUser = (user) => nameLens.set(user, 'New Name');

   // Avoid - creates new lens every call
   const updateUser = (user) => lens('name').set(user, 'New Name');
   ```

2. **Use lensPath for deep nesting:**
   ```javascript
   // Good - single lens
   const cityLens = lensPath(['address', 'location', 'city']);

   // Avoid - manual composition
   const cityLens = lens('address')
     .compose(lens('location'))
     .compose(lens('city'));
   ```

3. **Combine with transducers for large datasets:**
   ```javascript
   // Process millions of records in bounded memory
   const nameLens = lens('name');
   const normalized = new Pipeline()
     .map(user => nameLens.over(user, name => name.trim()))
     .filter(user => user.active)
     .toArray(largeDataset);
   ```

---

## Advanced Optics

Orlando provides a complete optics hierarchy beyond basic lenses. Each optic type is designed for a specific data access pattern.

### Prism

A Prism focuses on a value that may or may not exist within a sum type (tagged union, enum variant). Use prisms when your data has multiple possible shapes and you want to safely access one variant.

#### `prism(matchFn, buildFn)`

Create a prism from match and build functions.

```typescript
prism(matchFn: (source: any) => any | undefined, buildFn: (value: any) => any): JsPrism
```

**Parameters:**
- `matchFn` - A function that extracts the variant's value, or returns `undefined` if it doesn't match
- `buildFn` - A function that constructs the sum type from a value

**Example:**
```javascript
import { prism } from 'orlando-transducers';

// Prism for Result-like tagged unions
const okPrism = prism(
  obj => obj.tag === 'ok' ? obj.value : undefined,
  value => ({ tag: 'ok', value })
);

okPrism.preview({ tag: 'ok', value: 42 });     // 42
okPrism.preview({ tag: 'err', error: 'x' });   // undefined
okPrism.review(99);                             // { tag: 'ok', value: 99 }

// over only applies when the prism matches
okPrism.over({ tag: 'ok', value: 10 }, x => x * 2);
// { tag: 'ok', value: 20 }

okPrism.over({ tag: 'err', error: 'x' }, x => x * 2);
// { tag: 'err', error: 'x' } (unchanged)
```

**Use cases:**
- Accessing specific variants in tagged unions
- Safely transforming optional/nullable structures
- Pattern matching on discriminated types

---

#### Prism Methods

##### `preview(source)`

Try to extract the focused variant from the source.

```typescript
preview(source: any): any | undefined
```

Returns the focused value if the prism matches, or `undefined` if it doesn't.

---

##### `review(value)`

Construct the sum type from the focused value.

```typescript
review(value: any): any
```

---

##### `over(source, fn)`

Transform the focused variant using a function. If the prism doesn't match, returns the source unchanged.

```typescript
over(source: any, fn: (value: any) => any): any
```

---

### Iso

An Iso (isomorphism) represents a lossless bidirectional conversion between two representations. The conversion must be invertible: `from(to(x)) === x` and `to(from(y)) === y`.

#### `iso(toFn, fromFn)`

Create an isomorphism from a pair of inverse functions.

```typescript
iso(toFn: (source: any) => any, fromFn: (target: any) => any): JsIso
```

**Parameters:**
- `toFn` - A function that converts source → target
- `fromFn` - A function that converts target → source (must be the inverse of `toFn`)

**Example:**
```javascript
import { iso } from 'orlando-transducers';

// Celsius ↔ Fahrenheit
const tempIso = iso(
  c => c * 9 / 5 + 32,    // to: Celsius → Fahrenheit
  f => (f - 32) * 5 / 9   // from: Fahrenheit → Celsius
);

tempIso.to(100);    // 212
tempIso.from(32);   // 0

// over: convert, transform in target space, convert back
tempIso.over(0, f => f + 10);  // ~5.56 (add 10°F, result in Celsius)

// Reverse the iso
const fahrenheitCelsius = tempIso.reverse();
fahrenheitCelsius.to(212);  // 100
```

**Use cases:**
- Unit conversions (temperature, currency, distance)
- Encoding/decoding (JSON ↔ object, base64 ↔ binary)
- Newtype wrappers

---

#### Iso Methods

##### `to(source)`

Convert from source representation to target.

```typescript
to(source: any): any
```

---

##### `from(value)`

Convert from target representation back to source.

```typescript
from(value: any): any
```

---

##### `over(source, fn)`

Transform via the isomorphism: convert to target, apply `fn`, convert back.

```typescript
over(source: any, fn: (target: any) => any): any
```

---

##### `reverse()`

Return a new Iso with the `to` and `from` directions swapped.

```typescript
reverse(): JsIso
```

---

### Fold

A Fold is a read-only optic that extracts zero or more values from a structure. Unlike a Lens (which focuses on exactly one value) or a Traversal (which can also write), a Fold is purely for reading.

#### `fold(extractFn)`

Create a fold from an extraction function.

```typescript
fold(extractFn: (source: any) => any[]): JsFold
```

**Parameters:**
- `extractFn` - A function that returns an array of extracted values from the source

**Example:**
```javascript
import { fold } from 'orlando-transducers';

// Extract all values from an object
const valuesFold = fold(obj => Object.values(obj));

valuesFold.foldOf({ a: 1, b: 2, c: 3 });  // [1, 2, 3]
valuesFold.length({ a: 1, b: 2, c: 3 });   // 3
valuesFold.first({ a: 1, b: 2, c: 3 });    // 1
valuesFold.isEmpty({});                      // true

// Fold over nested arrays
const flatFold = fold(arr => arr.flat());
flatFold.foldOf([[1, 2], [3, 4]]);  // [1, 2, 3, 4]
```

**Use cases:**
- Aggregating values from complex structures
- Counting elements matching a pattern
- Extracting the first match from a collection

---

#### Fold Methods

##### `foldOf(source)`

Extract all focused values from the source.

```typescript
foldOf(source: any): any[]
```

---

##### `isEmpty(source)`

Check whether the fold extracts zero values.

```typescript
isEmpty(source: any): boolean
```

---

##### `length(source)`

Count how many values the fold extracts.

```typescript
length(source: any): number
```

---

##### `first(source)`

Extract the first focused value, or `undefined` if empty.

```typescript
first(source: any): any | undefined
```

---

### Traversal

A Traversal focuses on multiple values within a structure, supporting both read and write. It generalizes a Lens to work over collections.

#### `traversal(getAllFn, overAllFn)`

Create a traversal from get-all and over-all functions.

```typescript
traversal(
  getAllFn: (source: any) => any[],
  overAllFn: (source: any, fn: (value: any) => any) => any
): JsTraversal
```

**Parameters:**
- `getAllFn` - A function that extracts all focused values from the source
- `overAllFn` - A function that applies a transformation to all focused values and returns a new structure

**Example:**
```javascript
import { traversal } from 'orlando-transducers';

// Traversal over array elements
const elemTraversal = traversal(
  arr => arr,
  (arr, fn) => arr.map(v => fn(v))
);

const nums = [1, 2, 3, 4];
elemTraversal.getAll(nums);                  // [1, 2, 3, 4]
elemTraversal.setAll(nums, 0);               // [0, 0, 0, 0]
elemTraversal.overAll(nums, x => x * 10);    // [10, 20, 30, 40]

// Traversal over object values
const valuesTraversal = traversal(
  obj => Object.values(obj),
  (obj, fn) => Object.fromEntries(
    Object.entries(obj).map(([k, v]) => [k, fn(v)])
  )
);

valuesTraversal.getAll({ x: 1, y: 2 });               // [1, 2]
valuesTraversal.overAll({ x: 1, y: 2 }, n => n + 10);  // { x: 11, y: 12 }
```

**Use cases:**
- Transforming all elements in a collection
- Updating nested arrays within objects
- Batch modifications to homogeneous structures

---

#### Traversal Methods

##### `getAll(source)`

Extract all focused values.

```typescript
getAll(source: any): any[]
```

---

##### `setAll(source, value)`

Replace all focused values with a single value.

```typescript
setAll(source: any, value: any): any
```

---

##### `overAll(source, fn)`

Transform all focused values using a function.

```typescript
overAll(source: any, fn: (value: any) => any): any
```

---

## Pipeline Enhancements

JavaScript-specific convenience methods for common data transformation patterns.

### `pluck(key)`

Extract a single property from each object in the stream. Equivalent to `.map(x => x[key])`.

```typescript
pluck(key: string): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline().pluck('name');
pipeline.toArray([
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 }
]);
// ['Alice', 'Bob']
```

**Use cases:**
- Extracting IDs from objects
- Pulling out a single field for aggregation
- Quick property access in data pipelines

---

### `project(keys)`

Extract multiple properties from each object, creating new objects with only those keys.

```typescript
project(keys: string[]): Pipeline
```

**Example:**
```javascript
const pipeline = new Pipeline().project(['id', 'name']);
pipeline.toArray([
  { id: 1, name: 'Alice', age: 30, email: 'alice@test.com' },
  { id: 2, name: 'Bob', age: 25, email: 'bob@test.com' }
]);
// [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]
```

**Use cases:**
- Selecting fields for API responses
- Reducing object size before serialization
- Creating view models from full data objects

---

### `compact()`

Remove all falsy values from the stream.

```typescript
compact(): Pipeline
```

Filters out: `null`, `undefined`, `false`, `0`, `NaN`, and `''` (empty string).

**Example:**
```javascript
const pipeline = new Pipeline().compact();
pipeline.toArray([1, null, 'hello', undefined, 0, false, '', 42]);
// [1, 'hello', 42]
```

**Use cases:**
- Cleaning up sparse data
- Removing empty/null entries from API responses
- Filtering out zero values from numeric data

---

### `flatten(depth)`

Flatten nested arrays to a given depth.

```typescript
flatten(depth: number): Pipeline
```

**Parameters:**
- `depth` - Maximum depth to flatten. Use `1` for a single level.

**Example:**
```javascript
const pipeline = new Pipeline().flatten(1);
pipeline.toArray([[1, 2], [3, [4, 5]], [6]]);
// [1, 2, 3, [4, 5], 6]

const deep = new Pipeline().flatten(2);
deep.toArray([[1, 2], [3, [4, 5]], [6]]);
// [1, 2, 3, 4, 5, 6]
```

**Use cases:**
- Normalizing nested data structures
- Flattening grouped results
- Processing tree-like data

---

### `whereMatches(spec)`

Filter objects that match all properties in a spec object. Uses strict equality for comparison.

```typescript
whereMatches(spec: object): Pipeline
```

**Parameters:**
- `spec` - A JavaScript object whose key-value pairs must all match

**Example:**
```javascript
const pipeline = new Pipeline().whereMatches({ active: true, role: 'admin' });
pipeline.toArray([
  { name: 'Alice', active: true, role: 'admin' },
  { name: 'Bob', active: false, role: 'user' },
  { name: 'Charlie', active: true, role: 'user' }
]);
// [{ name: 'Alice', active: true, role: 'admin' }]
```

**Use cases:**
- Filtering records by multiple criteria
- Pattern matching on object shapes
- Declarative query-like filtering

---

## Optics-Pipeline Integration

Use lenses directly within pipelines for focused, composable data transformations. These methods avoid the overhead of creating intermediate JavaScript functions.

### `viewLens(lens)`

Apply a lens to extract the focused value from each element. Equivalent to `.map(x => myLens.get(x))`.

```typescript
viewLens(lens: JsLens): Pipeline
```

**Example:**
```javascript
import { lens, Pipeline } from 'orlando-transducers';

const nameLens = lens('name');
const pipeline = new Pipeline().viewLens(nameLens);
pipeline.toArray([{ name: 'Alice', age: 30 }, { name: 'Bob', age: 25 }]);
// ['Alice', 'Bob']

// Compose with other pipeline operations
const pipeline2 = new Pipeline()
  .viewLens(nameLens)
  .filter(name => name.length > 3)
  .take(2);
```

---

### `overLens(lens, fn)`

Transform each element's focused value through a lens. The rest of each object is preserved unchanged.

```typescript
overLens(lens: JsLens, fn: (value: any) => any): Pipeline
```

**Example:**
```javascript
import { lens, Pipeline } from 'orlando-transducers';

const priceLens = lens('price');
const pipeline = new Pipeline().overLens(priceLens, p => p * 0.9);
pipeline.toArray([
  { name: 'Widget', price: 100 },
  { name: 'Gadget', price: 200 }
]);
// [{ name: 'Widget', price: 90 }, { name: 'Gadget', price: 180 }]
```

---

### `filterLens(lens, pred)`

Filter elements based on a predicate applied to the lens-focused value. Equivalent to `.filter(x => pred(myLens.get(x)))`.

```typescript
filterLens(lens: JsLens, pred: (value: any) => boolean): Pipeline
```

**Example:**
```javascript
import { lens, Pipeline } from 'orlando-transducers';

const ageLens = lens('age');
const pipeline = new Pipeline().filterLens(ageLens, a => a >= 18);
pipeline.toArray([
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 17 },
  { name: 'Charlie', age: 30 }
]);
// [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 }]
```

---

### `setLens(lens, value)`

Set the focused value of a lens on every element. Useful for bulk updates.

```typescript
setLens(lens: JsLens, value: any): Pipeline
```

**Example:**
```javascript
import { lens, Pipeline } from 'orlando-transducers';

const statusLens = lens('status');
const pipeline = new Pipeline().setLens(statusLens, 'published');
pipeline.toArray([
  { id: 1, status: 'draft' },
  { id: 2, status: 'draft' }
]);
// [{ id: 1, status: 'published' }, { id: 2, status: 'published' }]
```

---

## Geometric Optics

Operations on multivector coefficient arrays for Clifford algebras. These functions work with flat `Float64Array` coefficient arrays where each index corresponds to a basis blade (index = bitset of basis vectors, grade = popcount of bits).

A multivector in Cl(p,q,r) has `2^(p+q+r)` coefficients. For example, Cl(3,0,0) has 8 basis blades: scalar, e1, e2, e3, e12, e13, e23, e123.

### `bladeGrade(index)`

Compute the grade (number of basis vectors) of a basis blade from its bit-index.

```typescript
bladeGrade(index: number): number
```

**Example:**
```javascript
import { bladeGrade } from 'orlando-transducers';

bladeGrade(0);   // 0 (scalar: no basis vectors)
bladeGrade(1);   // 1 (e1: one basis vector)
bladeGrade(3);   // 2 (e12: two basis vectors, binary 0b11)
bladeGrade(7);   // 3 (e123: three basis vectors, binary 0b111)
bladeGrade(5);   // 2 (e13: two basis vectors, binary 0b101)
```

---

### `bladesAtGradeCount(dimension, grade)`

Count how many basis blades exist at a given grade in a given dimension.

```typescript
bladesAtGradeCount(dimension: number, grade: number): number
```

**Example:**
```javascript
import { bladesAtGradeCount } from 'orlando-transducers';

// In 3 dimensions:
bladesAtGradeCount(3, 0);  // 1  (scalar)
bladesAtGradeCount(3, 1);  // 3  (vectors: e1, e2, e3)
bladesAtGradeCount(3, 2);  // 3  (bivectors: e12, e13, e23)
bladesAtGradeCount(3, 3);  // 1  (trivector: e123)
```

---

### `gradeIndices(dimension, grade)`

Get the coefficient array indices for all basis blades at a given grade.

```typescript
gradeIndices(dimension: number, grade: number): number[]
```

**Example:**
```javascript
import { gradeIndices } from 'orlando-transducers';

gradeIndices(3, 0);  // [0]        (scalar at index 0)
gradeIndices(3, 1);  // [1, 2, 4]  (e1, e2, e3)
gradeIndices(3, 2);  // [3, 5, 6]  (e12, e13, e23)
gradeIndices(3, 3);  // [7]        (e123)
```

---

### `gradeExtract(dimension, grade, mv)`

Extract the coefficients of a specific grade from a multivector.

```typescript
gradeExtract(dimension: number, grade: number, mv: Float64Array): Float64Array
```

**Example:**
```javascript
import { gradeExtract } from 'orlando-transducers';

// Cl(3,0,0): [scalar, e1, e2, e3, e12, e13, e23, e123]
const mv = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);

gradeExtract(3, 0, mv);  // Float64Array [1]         (scalar)
gradeExtract(3, 1, mv);  // Float64Array [2, 3, 4]   (vectors)
gradeExtract(3, 2, mv);  // Float64Array [5, 6, 7]   (bivectors)
gradeExtract(3, 3, mv);  // Float64Array [8]          (trivector)
```

---

### `gradeProject(dimension, grade, mv)`

Project a multivector onto a single grade, zeroing out all other components.

```typescript
gradeProject(dimension: number, grade: number, mv: Float64Array): Float64Array
```

**Example:**
```javascript
import { gradeProject } from 'orlando-transducers';

const mv = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);

// Keep only the vector (grade 1) part
gradeProject(3, 1, mv);
// Float64Array [0, 2, 3, 0, 0, 0, 0, 0]
//               ^scalar zeroed    ^bivectors zeroed
```

---

### `gradeProjectMax(dimension, maxGrade, mv)`

Project a multivector onto all grades up to and including `maxGrade`.

```typescript
gradeProjectMax(dimension: number, maxGrade: number, mv: Float64Array): Float64Array
```

**Example:**
```javascript
import { gradeProjectMax } from 'orlando-transducers';

const mv = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);

// Keep scalar + vector parts (grades 0 and 1)
gradeProjectMax(3, 1, mv);
// Float64Array [1, 2, 3, 4, 0, 0, 0, 0]
```

---

### `gradeMask(dimension, mv)`

Return a bitmask indicating which grades have non-zero coefficients.

```typescript
gradeMask(dimension: number, mv: Float64Array): number
```

**Example:**
```javascript
import { gradeMask } from 'orlando-transducers';

const pureVector = new Float64Array([0, 1, 2, 3, 0, 0, 0, 0]);
gradeMask(3, pureVector);  // 0b0010 = 2 (only grade 1)

const mixed = new Float64Array([1, 0, 0, 0, 5, 6, 7, 0]);
gradeMask(3, mixed);  // 0b0101 = 5 (grades 0 and 2)
```

---

### `hasGrade(dimension, grade, mv)`

Check if a multivector has any non-zero coefficients at a given grade.

```typescript
hasGrade(dimension: number, grade: number, mv: Float64Array): boolean
```

---

### `isPureGrade(dimension, mv)`

Check if a multivector has non-zero coefficients at exactly one grade.

```typescript
isPureGrade(dimension: number, mv: Float64Array): boolean
```

**Example:**
```javascript
import { isPureGrade } from 'orlando-transducers';

const pureVector = new Float64Array([0, 1, 2, 3, 0, 0, 0, 0]);
isPureGrade(3, pureVector);  // true (only grade 1)

const mixed = new Float64Array([1, 1, 0, 0, 0, 0, 0, 0]);
isPureGrade(3, mixed);  // false (grades 0 and 1)
```

---

### `componentGet(mv, bladeIndex)`

Get the coefficient at a specific blade index.

```typescript
componentGet(mv: Float64Array, bladeIndex: number): number | undefined
```

---

### `componentSet(mv, bladeIndex, value)`

Return a new multivector with one coefficient changed.

```typescript
componentSet(mv: Float64Array, bladeIndex: number, value: number): Float64Array
```

---

### `mvNorm(mv)`

Compute the magnitude (Euclidean norm) of a multivector.

```typescript
mvNorm(mv: Float64Array): number
```

**Example:**
```javascript
import { mvNorm } from 'orlando-transducers';

const mv = new Float64Array([3, 4, 0, 0]);
mvNorm(mv);  // 5.0
```

---

### `mvNormSquared(mv)`

Compute the squared magnitude (avoids the square root).

```typescript
mvNormSquared(mv: Float64Array): number
```

---

### `mvNormalize(mv)`

Normalize a multivector to unit length. Returns `undefined` if the norm is zero.

```typescript
mvNormalize(mv: Float64Array): Float64Array | undefined
```

**Example:**
```javascript
import { mvNormalize } from 'orlando-transducers';

const mv = new Float64Array([3, 4, 0, 0]);
mvNormalize(mv);  // Float64Array [0.6, 0.8, 0, 0]
```

---

### `gradeInvolution(dimension, mv)`

Apply grade involution: grade `k` coefficients are multiplied by `(-1)^k`.

```typescript
gradeInvolution(dimension: number, mv: Float64Array): Float64Array
```

**Example:**
```javascript
import { gradeInvolution } from 'orlando-transducers';

// [scalar, e1, e2, e3, e12, e13, e23, e123]
const mv = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);
gradeInvolution(3, mv);
// [1, -2, -3, -4, 5, 6, 7, -8]
// grade 0: +1, grade 1: -1, grade 2: +1, grade 3: -1
```

---

### `mvReverse(dimension, mv)`

Apply the reverse operation: grade `k` coefficients are multiplied by `(-1)^(k(k-1)/2)`.

```typescript
mvReverse(dimension: number, mv: Float64Array): Float64Array
```

**Example:**
```javascript
import { mvReverse } from 'orlando-transducers';

const mv = new Float64Array([1, 2, 3, 4, 5, 6, 7, 8]);
mvReverse(3, mv);
// [1, 2, 3, 4, -5, -6, -7, -8]
// grade 0: +1, grade 1: +1, grade 2: -1, grade 3: -1
```

---

## Next Steps

- Check out the [Hybrid Composition Guide]../HYBRID_COMPOSITION.md for combining transducers with multi-input operations
- See the [Migration Guide]./MIGRATION.md for converting from array methods
- Read the [Main README]../../README.md for project overview

---

**Questions?** [Open an issue](https://github.com/justinelliottcobb/Orlando/issues) on GitHub.