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
# Migration Guide: From Array Methods to Orlando Transducers

A practical guide for converting JavaScript array operations to Orlando transducers.

## Table of Contents

- [Why Migrate?]#why-migrate
- [Basic Conversions]#basic-conversions
- [Common Patterns]#common-patterns
- [Performance Gotchas]#performance-gotchas
- [Advanced Patterns]#advanced-patterns
- [Troubleshooting]#troubleshooting

## Why Migrate?

### Array Methods Create Intermediate Arrays

```javascript
// ❌ Traditional approach - creates 2 intermediate arrays
const result = data
  .map(x => x * 2)        // Intermediate array 1
  .filter(x => x > 10)    // Intermediate array 2
  .slice(0, 5);           // Final result
```

**Problems:**
- Memory allocation for each step
- Full iteration even if you only need first N results
- Garbage collection overhead

### Orlando Processes in a Single Pass

```javascript
// ✅ Orlando approach - single pass, no intermediates
import init, { Pipeline } from 'orlando-transducers';
await init();

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

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

**Benefits:**
- No intermediate allocations
- Early termination (stops after collecting 5 elements)
- Single pass over data
- WASM-powered performance

## Basic Conversions

### Map

**Before (Array):**
```javascript
const doubled = numbers.map(x => x * 2);
```

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

const doubled = pipeline.toArray(numbers);
```

---

### Filter

**Before (Array):**
```javascript
const evens = numbers.filter(x => x % 2 === 0);
```

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

const evens = pipeline.toArray(numbers);
```

---

### Map + Filter

**Before (Array):**
```javascript
const result = numbers
  .map(x => x * 2)
  .filter(x => x > 10);
```

**After (Orlando):**
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2)
  .filter(x => x > 10);

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

---

### Take (slice)

**Before (Array):**
```javascript
const first5 = numbers.slice(0, 5);
```

**After (Orlando):**
```javascript
const pipeline = new Pipeline()
  .take(5);

const first5 = pipeline.toArray(numbers);
```

**💡 Performance Win:** Orlando stops processing after 5 elements. Array methods process everything first, then slice.

---

### Drop (slice)

**Before (Array):**
```javascript
const skip3 = numbers.slice(3);
```

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

const skip3 = pipeline.toArray(numbers);
```

---

### Find First

**Before (Array):**
```javascript
const first = numbers.find(x => x > 100);
```

**After (Orlando):**
```javascript
const pipeline = new Pipeline()
  .filter(x => x > 100)
  .take(1);

const result = pipeline.toArray(numbers);
const first = result[0]; // or undefined
```

**💡 Performance Win:** Orlando stops immediately after finding the first match.

---

### Reduce (Sum)

**Before (Array):**
```javascript
const sum = numbers.reduce((acc, x) => acc + x, 0);
```

**After (Orlando):**
```javascript
const pipeline = new Pipeline()
  .map(x => x); // or apply transformations

const sum = pipeline.reduce(
  numbers,
  (acc, x) => acc + x,
  0
);
```

---

## Common Patterns

### Pagination

**Before (Array):**
```javascript
function paginate(data, page, pageSize) {
  const start = (page - 1) * pageSize;
  return data.slice(start, start + pageSize);
}

const page2 = paginate(users, 2, 20);
```

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

const page2 = paginate(users, 2, 20);
```

**💡 Performance Win:** Orlando only processes the exact slice needed, not the entire array.

---

### Data Transformation Pipeline

**Before (Array):**
```javascript
const activeCompanyEmails = users
  .filter(user => user.active)
  .map(user => ({
    id: user.id,
    email: user.email.toLowerCase()
  }))
  .filter(user => user.email.endsWith('@company.com'))
  .map(user => user.email)
  .slice(0, 100);
```

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

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

**💡 Performance Win:**
- Single pass (no intermediate arrays)
- Early termination (stops at 100 emails)
- WASM-powered execution

---

### Search with Multiple Filters

**Before (Array):**
```javascript
const searchProducts = (products, filters) => {
  return products
    .filter(p => p.category === filters.category)
    .filter(p => p.price >= filters.minPrice)
    .filter(p => p.price <= filters.maxPrice)
    .filter(p => p.rating >= filters.minRating)
    .filter(p => p.inStock)
    .slice(0, filters.limit || 20);
};
```

**After (Orlando):**
```javascript
const searchProducts = (products, filters) => {
  const pipeline = new Pipeline()
    .filter(p => p.category === filters.category)
    .filter(p => p.price >= filters.minPrice)
    .filter(p => p.price <= filters.maxPrice)
    .filter(p => p.rating >= filters.minRating)
    .filter(p => p.inStock)
    .take(filters.limit || 20);

  return pipeline.toArray(products);
};
```

---

### Analytics Aggregation

**Before (Array):**
```javascript
// Calculate total revenue from purchases
const purchases = events
  .filter(e => e.type === 'purchase')
  .map(e => e.amount);

const totalRevenue = purchases.reduce((sum, amt) => sum + amt, 0);
```

**After (Orlando):**
```javascript
const pipeline = new Pipeline()
  .filter(e => e.type === 'purchase')
  .map(e => e.amount);

const totalRevenue = pipeline.reduce(
  events,
  (sum, amt) => sum + amt,
  0
);
```

---

### Top N with Sorting

**Before (Array):**
```javascript
const top10 = products
  .filter(p => p.inStock)
  .sort((a, b) => b.sales - a.sales)
  .slice(0, 10);
```

**After (Orlando):**
```javascript
// Note: Orlando doesn't have built-in sort (sorting requires seeing all data)
// For this pattern, sort BEFORE the pipeline or use a hybrid approach

const sorted = products
  .filter(p => p.inStock)
  .sort((a, b) => b.sales - a.sales);

const top10 = new Pipeline()
  .take(10)
  .toArray(sorted);

// Or use array sort, then Orlando for rest of pipeline
const top10 = new Pipeline()
  .filter(p => p.inStock)
  .toArray(products)
  .sort((a, b) => b.sales - a.sales)
  .slice(0, 10);
```

**⚠️ Note:** Transducers are best for operations that don't require seeing all data at once. For sorting, use array methods or sort before/after the pipeline.

---

## Performance Gotchas

### 1. Small Datasets (<100 elements)

**Array methods may be faster!**

```javascript
// For small data, array methods have less overhead
const small = [1, 2, 3, 4, 5];

// This is fine (overhead is negligible)
const result = small.map(x => x * 2).filter(x => x > 5);

// Orlando overhead may not be worth it for tiny datasets
```

**Rule of thumb:** Use Orlando for datasets >1000 elements or complex pipelines.

---

### 2. Single Operation

**Array methods are simpler for single operations:**

```javascript
// ❌ Overkill for single operation
const doubled = new Pipeline()
  .map(x => x * 2)
  .toArray(numbers);

// ✅ Just use array method
const doubled = numbers.map(x => x * 2);
```

**Use Orlando when:** You have 2+ operations, especially with early termination.

---

### 3. Need All Data Anyway

**If processing everything, Orlando advantage is smaller:**

```javascript
// If you need all 1M results anyway, Orlando is still faster but less dramatic
const allDoubled = new Pipeline()
  .map(x => x * 2)
  .toArray(oneMillion);

// vs
const allDoubled = oneMillion.map(x => x * 2);

// Orlando still wins (no intermediate arrays), but margin is smaller
```

**Biggest wins:** Early termination scenarios (take, takeWhile, find first).

---

## Advanced Patterns

### Reusable Pipelines

**Before (Array):**
```javascript
// Have to repeat the chain
const activeUsers1 = users1.filter(u => u.active).map(u => u.email);
const activeUsers2 = users2.filter(u => u.active).map(u => u.email);
```

**After (Orlando):**
```javascript
// Define once, reuse many times
const activeEmailPipeline = new Pipeline()
  .filter(u => u.active)
  .map(u => u.email);

const activeUsers1 = activeEmailPipeline.toArray(users1);
const activeUsers2 = activeEmailPipeline.toArray(users2);
const activeUsers3 = activeEmailPipeline.toArray(users3);
```

---

### Debugging with Tap

**Before (Array):**
```javascript
const result = data
  .map(x => {
    console.log('Input:', x);
    return x * 2;
  })
  .filter(x => {
    console.log('After map:', x);
    return x > 10;
  });
```

**After (Orlando):**
```javascript
const pipeline = 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));

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

---

### Conditional Pipelines

**Before (Array):**
```javascript
let result = data.map(x => x * 2);

if (needsFiltering) {
  result = result.filter(x => x > 10);
}

if (limit) {
  result = result.slice(0, limit);
}
```

**After (Orlando):**
```javascript
let pipeline = new Pipeline()
  .map(x => x * 2);

if (needsFiltering) {
  pipeline = pipeline.filter(x => x > 10);
}

if (limit) {
  pipeline = pipeline.take(limit);
}

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

---

## Troubleshooting

### "Pipeline is not iterable"

**Problem:**
```javascript
// ❌ Won't work
for (const item of pipeline) {
  console.log(item);
}
```

**Solution:**
Pipelines are not iterables. Use `.toArray()` to execute:

```javascript
// ✅ Correct
const result = pipeline.toArray(data);
for (const item of result) {
  console.log(item);
}
```

---

### "Cannot read property of undefined"

**Problem:**
```javascript
const pipeline = new Pipeline();
const result = pipeline.toArray(); // ❌ Missing source data
```

**Solution:**
Always provide source data to terminal operations:

```javascript
const result = pipeline.toArray(data); // ✅ Provide data
```

---

### Type Errors in TypeScript

**Problem:**
```javascript
const pipeline = new Pipeline()
  .map(x => x * 2)  // x is 'any'
  .filter(x => x.length > 0); // Runtime error if x is number
```

**Solution:**
Add type annotations to your functions:

```typescript
const pipeline = new Pipeline()
  .map((x: number) => x * 2)
  .filter((x: number) => x > 10);
```

---

### Performance Not Improving

**Check:**
1. **Dataset size:** Orlando shines on large datasets (>1000 elements)
2. **Early termination:** Are you using `take` or `takeWhile`?
3. **Complexity:** Single operations may not benefit much
4. **Initialization:** Are you reusing pipelines or creating new ones each time?

**Good scenario for Orlando:**
```javascript
// Large dataset + complex pipeline + early termination
const result = new Pipeline()
  .map(/* expensive operation */)
  .filter(/* complex condition */)
  .map(/* another transformation */)
  .take(10)  // Early termination!
  .toArray(millionItems);
```

**Not ideal for Orlando:**
```javascript
// Small dataset + single operation
const result = new Pipeline()
  .map(x => x * 2)
  .toArray([1, 2, 3, 4, 5]);
```

---

## Summary: When to Use Orlando

### ✅ Great for:
- Large datasets (>1000 elements)
- Complex pipelines (3+ operations)
- Early termination scenarios (take, takeWhile)
- Reusable transformation pipelines
- Performance-critical code
- Reducing memory allocations

### ⚠️ Consider array methods for:
- Small datasets (<100 elements)
- Single operations
- Prototyping / quick scripts
- When you need array methods not in Orlando (e.g., sort, reverse)

---

## Immutable Nested Updates with Optics

Orlando's optics replace verbose manual spreading for immutable updates.

### Simple Property Update

**Before (Spread):**
```javascript
const updated = { ...user, name: "Bob" };
```

**After (Orlando):**
```javascript
import { lens } from 'orlando-transducers';

const nameLens = lens('name');
const updated = nameLens.set(user, "Bob");
```

### Deep Nested Update

**Before (Spread):**
```javascript
const updated = {
  ...state,
  user: {
    ...state.user,
    address: {
      ...state.user.address,
      city: "Boston"
    }
  }
};
```

**After (Orlando):**
```javascript
import { lensPath } from 'orlando-transducers';

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

### Transform In Place

**Before (Spread):**
```javascript
const updated = { ...user, age: user.age + 1 };
```

**After (Orlando):**
```javascript
const ageLens = lens('age');
const updated = ageLens.over(user, age => age + 1);
```

### Nullable Fields with Optional

**Before (Manual check):**
```javascript
const phone = user.phone != null ? user.phone : "N/A";
const updated = user.phone != null
  ? { ...user, phone: normalize(user.phone) }
  : user;
```

**After (Orlando):**
```javascript
import { optional } from 'orlando-transducers';

const phoneLens = optional('phone');
const phone = phoneLens.getOr(user, "N/A");
const updated = phoneLens.over(user, normalize); // no-op if undefined
```

---

## Next Steps

- Read the [JavaScript API Documentation]./JAVASCRIPT.md
- Try the [Interactive Demo]../../examples/index.html
- Run [Performance Benchmarks]../../examples/performance.html
- Explore [Real-World Examples]../../examples/data-processing.html