iterflow 0.9.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -194
- package/dist/fn/index.cjs +26 -3
- package/dist/fn/index.cjs.map +1 -1
- package/dist/fn/index.d.cts +1 -3
- package/dist/fn/index.d.ts +1 -3
- package/dist/fn/index.js +26 -3
- package/dist/fn/index.js.map +1 -1
- package/dist/index.cjs +324 -10
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1058 -17
- package/dist/index.d.ts +1058 -17
- package/dist/index.js +324 -10
- package/dist/index.js.map +1 -1
- package/package.json +13 -5
package/dist/index.d.ts
CHANGED
|
@@ -313,13 +313,28 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
313
313
|
* This method is only available when T is number.
|
|
314
314
|
* This is a terminal operation that consumes the iterator.
|
|
315
315
|
*
|
|
316
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
317
|
+
* for sorting. For large datasets, consider using streaming alternatives or limiting data size.
|
|
318
|
+
*
|
|
316
319
|
* @param this - iterflow instance constrained to numbers
|
|
317
320
|
* @returns The median value, or undefined if the iterator is empty
|
|
318
321
|
* @example
|
|
319
322
|
* ```typescript
|
|
323
|
+
* // SAFE: Small dataset
|
|
320
324
|
* iter([1, 2, 3, 4, 5]).median(); // 3
|
|
321
325
|
* iter([1, 2, 3, 4]).median(); // 2.5
|
|
322
|
-
*
|
|
326
|
+
*
|
|
327
|
+
* // SAFE: Limit data before median
|
|
328
|
+
* iter(largeDataset).take(1000).median();
|
|
329
|
+
*
|
|
330
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
331
|
+
* iter(millionRecords).median(); // Materializes all records!
|
|
332
|
+
*
|
|
333
|
+
* // SAFE: Process in chunks
|
|
334
|
+
* iter(largeDataset)
|
|
335
|
+
* .chunk(1000)
|
|
336
|
+
* .map(chunk => iter(chunk).median())
|
|
337
|
+
* .toArray();
|
|
323
338
|
* ```
|
|
324
339
|
*/
|
|
325
340
|
median(this: iterflow<number>): number | undefined;
|
|
@@ -329,12 +344,28 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
329
344
|
* This method is only available when T is number.
|
|
330
345
|
* This is a terminal operation that consumes the iterator.
|
|
331
346
|
*
|
|
347
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
348
|
+
* to calculate variance. For large datasets, consider using streaming variance algorithms
|
|
349
|
+
* or limiting data size.
|
|
350
|
+
*
|
|
332
351
|
* @param this - iterflow instance constrained to numbers
|
|
333
352
|
* @returns The variance, or undefined if the iterator is empty
|
|
334
353
|
* @example
|
|
335
354
|
* ```typescript
|
|
355
|
+
* // SAFE: Small dataset
|
|
336
356
|
* iter([1, 2, 3, 4, 5]).variance(); // 2
|
|
337
|
-
*
|
|
357
|
+
*
|
|
358
|
+
* // SAFE: Limit data before variance
|
|
359
|
+
* iter(largeDataset).take(10000).variance();
|
|
360
|
+
*
|
|
361
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
362
|
+
* iter(millionRecords).variance(); // Materializes all records!
|
|
363
|
+
*
|
|
364
|
+
* // SAFE: Process in windows
|
|
365
|
+
* iter(largeDataset)
|
|
366
|
+
* .window(1000)
|
|
367
|
+
* .map(window => iter(window).variance())
|
|
368
|
+
* .toArray();
|
|
338
369
|
* ```
|
|
339
370
|
*/
|
|
340
371
|
variance(this: iterflow<number>): number | undefined;
|
|
@@ -344,12 +375,28 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
344
375
|
* This method is only available when T is number.
|
|
345
376
|
* This is a terminal operation that consumes the iterator.
|
|
346
377
|
*
|
|
378
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
379
|
+
* via variance calculation. For large datasets, consider using streaming algorithms
|
|
380
|
+
* or limiting data size.
|
|
381
|
+
*
|
|
347
382
|
* @param this - iterflow instance constrained to numbers
|
|
348
383
|
* @returns The standard deviation, or undefined if the iterator is empty
|
|
349
384
|
* @example
|
|
350
385
|
* ```typescript
|
|
386
|
+
* // SAFE: Small dataset
|
|
351
387
|
* iter([2, 4, 4, 4, 5, 5, 7, 9]).stdDev(); // ~2
|
|
352
|
-
*
|
|
388
|
+
*
|
|
389
|
+
* // SAFE: Limit data before stdDev
|
|
390
|
+
* iter(largeDataset).take(10000).stdDev();
|
|
391
|
+
*
|
|
392
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
393
|
+
* iter(millionRecords).stdDev(); // Materializes all records!
|
|
394
|
+
*
|
|
395
|
+
* // SAFE: Process in chunks
|
|
396
|
+
* iter(largeDataset)
|
|
397
|
+
* .chunk(1000)
|
|
398
|
+
* .map(chunk => iter(chunk).stdDev())
|
|
399
|
+
* .toArray();
|
|
353
400
|
* ```
|
|
354
401
|
*/
|
|
355
402
|
stdDev(this: iterflow<number>): number | undefined;
|
|
@@ -359,15 +406,30 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
359
406
|
* This method is only available when T is number.
|
|
360
407
|
* This is a terminal operation that consumes the iterator.
|
|
361
408
|
*
|
|
409
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
410
|
+
* for sorting. For large datasets, consider using approximate percentile algorithms
|
|
411
|
+
* or limiting data size.
|
|
412
|
+
*
|
|
362
413
|
* @param this - iterflow instance constrained to numbers
|
|
363
414
|
* @param p - The percentile to calculate (0-100)
|
|
364
415
|
* @returns The percentile value, or undefined if the iterator is empty
|
|
365
416
|
* @throws {Error} If p is not between 0 and 100
|
|
366
417
|
* @example
|
|
367
418
|
* ```typescript
|
|
419
|
+
* // SAFE: Small dataset
|
|
368
420
|
* iter([1, 2, 3, 4, 5]).percentile(50); // 3 (median)
|
|
369
421
|
* iter([1, 2, 3, 4, 5]).percentile(75); // 4
|
|
370
|
-
*
|
|
422
|
+
*
|
|
423
|
+
* // SAFE: Limit data before percentile
|
|
424
|
+
* iter(largeDataset).take(10000).percentile(95);
|
|
425
|
+
*
|
|
426
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
427
|
+
* iter(millionRecords).percentile(99); // Materializes all records!
|
|
428
|
+
*
|
|
429
|
+
* // SAFE: Sample for approximate percentile
|
|
430
|
+
* iter(largeDataset)
|
|
431
|
+
* .filter(() => Math.random() < 0.01) // 1% sample
|
|
432
|
+
* .percentile(95);
|
|
371
433
|
* ```
|
|
372
434
|
*/
|
|
373
435
|
percentile(this: iterflow<number>, p: number): number | undefined;
|
|
@@ -377,13 +439,28 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
377
439
|
* This method is only available when T is number.
|
|
378
440
|
* This is a terminal operation that consumes the iterator.
|
|
379
441
|
*
|
|
442
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
443
|
+
* to count frequencies. For large datasets with many unique values, memory usage can be significant.
|
|
444
|
+
*
|
|
380
445
|
* @param this - iterflow instance constrained to numbers
|
|
381
446
|
* @returns An array of the most frequent value(s), or undefined if the iterator is empty
|
|
382
447
|
* @example
|
|
383
448
|
* ```typescript
|
|
449
|
+
* // SAFE: Small dataset
|
|
384
450
|
* iter([1, 2, 2, 3, 3, 3]).mode(); // [3]
|
|
385
451
|
* iter([1, 1, 2, 2, 3]).mode(); // [1, 2] (bimodal)
|
|
386
|
-
*
|
|
452
|
+
*
|
|
453
|
+
* // SAFE: Limit data before mode
|
|
454
|
+
* iter(largeDataset).take(10000).mode();
|
|
455
|
+
*
|
|
456
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
457
|
+
* iter(millionRecords).mode(); // Materializes all records!
|
|
458
|
+
*
|
|
459
|
+
* // SAFE: Process in chunks
|
|
460
|
+
* iter(largeDataset)
|
|
461
|
+
* .chunk(1000)
|
|
462
|
+
* .map(chunk => iter(chunk).mode())
|
|
463
|
+
* .toArray();
|
|
387
464
|
* ```
|
|
388
465
|
*/
|
|
389
466
|
mode(this: iterflow<number>): number[] | undefined;
|
|
@@ -393,13 +470,28 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
393
470
|
* This method is only available when T is number.
|
|
394
471
|
* This is a terminal operation that consumes the iterator.
|
|
395
472
|
*
|
|
473
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire iterator into memory
|
|
474
|
+
* for sorting and percentile calculation. For large datasets, consider using streaming
|
|
475
|
+
* quantile algorithms or limiting data size.
|
|
476
|
+
*
|
|
396
477
|
* @param this - iterflow instance constrained to numbers
|
|
397
478
|
* @returns An object with Q1, Q2, and Q3 values, or undefined if the iterator is empty
|
|
398
479
|
* @example
|
|
399
480
|
* ```typescript
|
|
481
|
+
* // SAFE: Small dataset
|
|
400
482
|
* iter([1, 2, 3, 4, 5, 6, 7, 8, 9]).quartiles();
|
|
401
483
|
* // { Q1: 3, Q2: 5, Q3: 7 }
|
|
402
|
-
*
|
|
484
|
+
*
|
|
485
|
+
* // SAFE: Limit data before quartiles
|
|
486
|
+
* iter(largeDataset).take(10000).quartiles();
|
|
487
|
+
*
|
|
488
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
489
|
+
* iter(millionRecords).quartiles(); // Materializes all records!
|
|
490
|
+
*
|
|
491
|
+
* // SAFE: Sample for approximate quartiles
|
|
492
|
+
* iter(largeDataset)
|
|
493
|
+
* .filter(() => Math.random() < 0.01) // 1% sample
|
|
494
|
+
* .quartiles();
|
|
403
495
|
* ```
|
|
404
496
|
*/
|
|
405
497
|
quartiles(this: iterflow<number>): {
|
|
@@ -443,13 +535,34 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
443
535
|
* This method is only available when T is number.
|
|
444
536
|
* This is a terminal operation that consumes the iterator.
|
|
445
537
|
*
|
|
538
|
+
* WARNING - Memory Intensive: This operation eagerly materializes both iterators into memory
|
|
539
|
+
* to calculate covariance. For large datasets, this doubles memory usage.
|
|
540
|
+
*
|
|
446
541
|
* @param this - iterflow instance constrained to numbers
|
|
447
542
|
* @param other - An iterable of numbers to compare with
|
|
448
543
|
* @returns The covariance, or undefined if either sequence is empty or sequences have different lengths
|
|
449
544
|
* @example
|
|
450
545
|
* ```typescript
|
|
546
|
+
* // SAFE: Small datasets
|
|
451
547
|
* iter([1, 2, 3, 4, 5]).covariance([2, 4, 6, 8, 10]); // 4
|
|
452
|
-
*
|
|
548
|
+
*
|
|
549
|
+
* // SAFE: Limit both sequences
|
|
550
|
+
* iter(largeDataset1).take(10000).covariance(
|
|
551
|
+
* iter(largeDataset2).take(10000).toArray()
|
|
552
|
+
* );
|
|
553
|
+
*
|
|
554
|
+
* // UNSAFE: Large datasets may cause memory issues
|
|
555
|
+
* iter(millionRecords1).covariance(millionRecords2); // Materializes both!
|
|
556
|
+
*
|
|
557
|
+
* // SAFE: Process in windows
|
|
558
|
+
* iter(largeDataset1)
|
|
559
|
+
* .window(1000)
|
|
560
|
+
* .map((window, i) =>
|
|
561
|
+
* iter(window).covariance(
|
|
562
|
+
* iter(largeDataset2).drop(i * 1000).take(1000).toArray()
|
|
563
|
+
* )
|
|
564
|
+
* )
|
|
565
|
+
* .toArray();
|
|
453
566
|
* ```
|
|
454
567
|
*/
|
|
455
568
|
covariance(this: iterflow<number>, other: Iterable<number>): number | undefined;
|
|
@@ -460,14 +573,32 @@ declare class iterflow<T> implements Iterable<T> {
|
|
|
460
573
|
* This method is only available when T is number.
|
|
461
574
|
* This is a terminal operation that consumes the iterator.
|
|
462
575
|
*
|
|
576
|
+
* WARNING - Memory Intensive: This operation eagerly materializes both iterators into memory
|
|
577
|
+
* to calculate correlation. For large datasets, this doubles memory usage.
|
|
578
|
+
*
|
|
463
579
|
* @param this - iterflow instance constrained to numbers
|
|
464
580
|
* @param other - An iterable of numbers to compare with
|
|
465
581
|
* @returns The correlation coefficient, or undefined if either sequence is empty or sequences have different lengths
|
|
466
582
|
* @example
|
|
467
583
|
* ```typescript
|
|
468
|
-
*
|
|
469
|
-
* iter([1, 2, 3]).correlation([
|
|
470
|
-
* iter([]).correlation([
|
|
584
|
+
* // SAFE: Small datasets
|
|
585
|
+
* iter([1, 2, 3, 4, 5]).correlation([2, 4, 6, 8, 10]); // 1 (perfect positive)
|
|
586
|
+
* iter([1, 2, 3]).correlation([3, 2, 1]); // -1 (perfect negative)
|
|
587
|
+
*
|
|
588
|
+
* // SAFE: Limit both sequences
|
|
589
|
+
* iter(largeDataset1).take(10000).correlation(
|
|
590
|
+
* iter(largeDataset2).take(10000).toArray()
|
|
591
|
+
* );
|
|
592
|
+
*
|
|
593
|
+
* // UNSAFE: Large datasets may cause memory issues
|
|
594
|
+
* iter(millionRecords1).correlation(millionRecords2); // Materializes both!
|
|
595
|
+
*
|
|
596
|
+
* // SAFE: Sample for approximate correlation
|
|
597
|
+
* iter(largeDataset1)
|
|
598
|
+
* .filter(() => Math.random() < 0.01)
|
|
599
|
+
* .correlation(
|
|
600
|
+
* iter(largeDataset2).filter(() => Math.random() < 0.01).toArray()
|
|
601
|
+
* );
|
|
471
602
|
* ```
|
|
472
603
|
*/
|
|
473
604
|
correlation(this: iterflow<number>, other: Iterable<number>): number | undefined;
|
|
@@ -1091,11 +1222,27 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1091
1222
|
* Calculates the median value of all numeric elements.
|
|
1092
1223
|
* This is a terminal operation that consumes the async iterator.
|
|
1093
1224
|
*
|
|
1225
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1226
|
+
* for sorting. For large datasets, consider using streaming alternatives or limiting data size.
|
|
1227
|
+
*
|
|
1094
1228
|
* @param this - async iterflow instance constrained to numbers
|
|
1095
1229
|
* @returns A promise of the median value, or undefined if empty
|
|
1096
1230
|
* @example
|
|
1097
1231
|
* ```typescript
|
|
1232
|
+
* // SAFE: Small dataset
|
|
1098
1233
|
* await asyncIter([1, 2, 3, 4, 5]).median(); // 3
|
|
1234
|
+
*
|
|
1235
|
+
* // SAFE: Limit data before median
|
|
1236
|
+
* await asyncIter(largeAsyncDataset).take(1000).median();
|
|
1237
|
+
*
|
|
1238
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1239
|
+
* await asyncIter(millionRecords).median(); // Materializes all records!
|
|
1240
|
+
*
|
|
1241
|
+
* // SAFE: Process in chunks
|
|
1242
|
+
* await asyncIter(largeAsyncDataset)
|
|
1243
|
+
* .chunk(1000)
|
|
1244
|
+
* .map(async chunk => await asyncIter(chunk).median())
|
|
1245
|
+
* .toArray();
|
|
1099
1246
|
* ```
|
|
1100
1247
|
*/
|
|
1101
1248
|
median(this: Asynciterflow<number>): Promise<number | undefined>;
|
|
@@ -1103,11 +1250,28 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1103
1250
|
* Calculates the variance of all numeric elements.
|
|
1104
1251
|
* This is a terminal operation that consumes the async iterator.
|
|
1105
1252
|
*
|
|
1253
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1254
|
+
* to calculate variance. For large datasets, consider using streaming variance algorithms
|
|
1255
|
+
* or limiting data size.
|
|
1256
|
+
*
|
|
1106
1257
|
* @param this - async iterflow instance constrained to numbers
|
|
1107
1258
|
* @returns A promise of the variance, or undefined if empty
|
|
1108
1259
|
* @example
|
|
1109
1260
|
* ```typescript
|
|
1261
|
+
* // SAFE: Small dataset
|
|
1110
1262
|
* await asyncIter([1, 2, 3, 4, 5]).variance(); // 2
|
|
1263
|
+
*
|
|
1264
|
+
* // SAFE: Limit data before variance
|
|
1265
|
+
* await asyncIter(largeAsyncDataset).take(10000).variance();
|
|
1266
|
+
*
|
|
1267
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1268
|
+
* await asyncIter(millionRecords).variance(); // Materializes all records!
|
|
1269
|
+
*
|
|
1270
|
+
* // SAFE: Process in windows
|
|
1271
|
+
* await asyncIter(largeAsyncDataset)
|
|
1272
|
+
* .window(1000)
|
|
1273
|
+
* .map(async window => await asyncIter(window).variance())
|
|
1274
|
+
* .toArray();
|
|
1111
1275
|
* ```
|
|
1112
1276
|
*/
|
|
1113
1277
|
variance(this: Asynciterflow<number>): Promise<number | undefined>;
|
|
@@ -1115,11 +1279,28 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1115
1279
|
* Calculates the standard deviation of all numeric elements.
|
|
1116
1280
|
* This is a terminal operation that consumes the async iterator.
|
|
1117
1281
|
*
|
|
1282
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1283
|
+
* via variance calculation. For large datasets, consider using streaming algorithms
|
|
1284
|
+
* or limiting data size.
|
|
1285
|
+
*
|
|
1118
1286
|
* @param this - async iterflow instance constrained to numbers
|
|
1119
1287
|
* @returns A promise of the standard deviation, or undefined if empty
|
|
1120
1288
|
* @example
|
|
1121
1289
|
* ```typescript
|
|
1290
|
+
* // SAFE: Small dataset
|
|
1122
1291
|
* await asyncIter([2, 4, 4, 4, 5, 5, 7, 9]).stdDev(); // ~2
|
|
1292
|
+
*
|
|
1293
|
+
* // SAFE: Limit data before stdDev
|
|
1294
|
+
* await asyncIter(largeAsyncDataset).take(10000).stdDev();
|
|
1295
|
+
*
|
|
1296
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1297
|
+
* await asyncIter(millionRecords).stdDev(); // Materializes all records!
|
|
1298
|
+
*
|
|
1299
|
+
* // SAFE: Process in chunks
|
|
1300
|
+
* await asyncIter(largeAsyncDataset)
|
|
1301
|
+
* .chunk(1000)
|
|
1302
|
+
* .map(async chunk => await asyncIter(chunk).stdDev())
|
|
1303
|
+
* .toArray();
|
|
1123
1304
|
* ```
|
|
1124
1305
|
*/
|
|
1125
1306
|
stdDev(this: Asynciterflow<number>): Promise<number | undefined>;
|
|
@@ -1127,13 +1308,29 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1127
1308
|
* Calculates the specified percentile of all numeric elements.
|
|
1128
1309
|
* This is a terminal operation that consumes the async iterator.
|
|
1129
1310
|
*
|
|
1311
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1312
|
+
* for sorting. For large datasets, consider using approximate percentile algorithms
|
|
1313
|
+
* or limiting data size.
|
|
1314
|
+
*
|
|
1130
1315
|
* @param this - async iterflow instance constrained to numbers
|
|
1131
1316
|
* @param p - The percentile to calculate (0-100)
|
|
1132
1317
|
* @returns A promise of the percentile value, or undefined if empty
|
|
1133
1318
|
* @throws {Error} If p is not between 0 and 100
|
|
1134
1319
|
* @example
|
|
1135
1320
|
* ```typescript
|
|
1321
|
+
* // SAFE: Small dataset
|
|
1136
1322
|
* await asyncIter([1, 2, 3, 4, 5]).percentile(50); // 3
|
|
1323
|
+
*
|
|
1324
|
+
* // SAFE: Limit data before percentile
|
|
1325
|
+
* await asyncIter(largeAsyncDataset).take(10000).percentile(95);
|
|
1326
|
+
*
|
|
1327
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1328
|
+
* await asyncIter(millionRecords).percentile(99); // Materializes all records!
|
|
1329
|
+
*
|
|
1330
|
+
* // SAFE: Sample for approximate percentile
|
|
1331
|
+
* await asyncIter(largeAsyncDataset)
|
|
1332
|
+
* .filter(async () => Math.random() < 0.01) // 1% sample
|
|
1333
|
+
* .percentile(95);
|
|
1137
1334
|
* ```
|
|
1138
1335
|
*/
|
|
1139
1336
|
percentile(this: Asynciterflow<number>, p: number): Promise<number | undefined>;
|
|
@@ -1141,11 +1338,27 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1141
1338
|
* Finds the most frequent value(s) in the dataset.
|
|
1142
1339
|
* This is a terminal operation that consumes the async iterator.
|
|
1143
1340
|
*
|
|
1341
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1342
|
+
* to count frequencies. For large datasets with many unique values, memory usage can be significant.
|
|
1343
|
+
*
|
|
1144
1344
|
* @param this - async iterflow instance constrained to numbers
|
|
1145
1345
|
* @returns A promise of an array of the most frequent value(s), or undefined if empty
|
|
1146
1346
|
* @example
|
|
1147
1347
|
* ```typescript
|
|
1348
|
+
* // SAFE: Small dataset
|
|
1148
1349
|
* await asyncIter([1, 2, 2, 3, 3, 3]).mode(); // [3]
|
|
1350
|
+
*
|
|
1351
|
+
* // SAFE: Limit data before mode
|
|
1352
|
+
* await asyncIter(largeAsyncDataset).take(10000).mode();
|
|
1353
|
+
*
|
|
1354
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1355
|
+
* await asyncIter(millionRecords).mode(); // Materializes all records!
|
|
1356
|
+
*
|
|
1357
|
+
* // SAFE: Process in chunks
|
|
1358
|
+
* await asyncIter(largeAsyncDataset)
|
|
1359
|
+
* .chunk(1000)
|
|
1360
|
+
* .map(async chunk => await asyncIter(chunk).mode())
|
|
1361
|
+
* .toArray();
|
|
1149
1362
|
* ```
|
|
1150
1363
|
*/
|
|
1151
1364
|
mode(this: Asynciterflow<number>): Promise<number[] | undefined>;
|
|
@@ -1153,12 +1366,28 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1153
1366
|
* Calculates the quartiles (Q1, Q2, Q3) of all numeric elements.
|
|
1154
1367
|
* This is a terminal operation that consumes the async iterator.
|
|
1155
1368
|
*
|
|
1369
|
+
* WARNING - Memory Intensive: This operation eagerly materializes the entire async iterator into memory
|
|
1370
|
+
* for sorting and percentile calculation. For large datasets, consider using streaming
|
|
1371
|
+
* quantile algorithms or limiting data size.
|
|
1372
|
+
*
|
|
1156
1373
|
* @param this - async iterflow instance constrained to numbers
|
|
1157
1374
|
* @returns A promise of an object with Q1, Q2, and Q3 values, or undefined if empty
|
|
1158
1375
|
* @example
|
|
1159
1376
|
* ```typescript
|
|
1377
|
+
* // SAFE: Small dataset
|
|
1160
1378
|
* await asyncIter([1, 2, 3, 4, 5, 6, 7, 8, 9]).quartiles();
|
|
1161
1379
|
* // { Q1: 3, Q2: 5, Q3: 7 }
|
|
1380
|
+
*
|
|
1381
|
+
* // SAFE: Limit data before quartiles
|
|
1382
|
+
* await asyncIter(largeAsyncDataset).take(10000).quartiles();
|
|
1383
|
+
*
|
|
1384
|
+
* // UNSAFE: Large dataset may cause memory issues
|
|
1385
|
+
* await asyncIter(millionRecords).quartiles(); // Materializes all records!
|
|
1386
|
+
*
|
|
1387
|
+
* // SAFE: Sample for approximate quartiles
|
|
1388
|
+
* await asyncIter(largeAsyncDataset)
|
|
1389
|
+
* .filter(async () => Math.random() < 0.01) // 1% sample
|
|
1390
|
+
* .quartiles();
|
|
1162
1391
|
* ```
|
|
1163
1392
|
*/
|
|
1164
1393
|
quartiles(this: Asynciterflow<number>): Promise<{
|
|
@@ -1194,12 +1423,34 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1194
1423
|
* Calculates the covariance between two numeric sequences.
|
|
1195
1424
|
* This is a terminal operation that consumes the async iterator.
|
|
1196
1425
|
*
|
|
1426
|
+
* WARNING - Memory Intensive: This operation eagerly materializes both async iterators into memory
|
|
1427
|
+
* to calculate covariance. For large datasets, this doubles memory usage.
|
|
1428
|
+
*
|
|
1197
1429
|
* @param this - async iterflow instance constrained to numbers
|
|
1198
1430
|
* @param other - An async iterable of numbers to compare with
|
|
1199
1431
|
* @returns A promise of the covariance, or undefined if sequences are empty or have different lengths
|
|
1200
1432
|
* @example
|
|
1201
1433
|
* ```typescript
|
|
1434
|
+
* // SAFE: Small datasets
|
|
1202
1435
|
* await asyncIter([1, 2, 3, 4, 5]).covariance([2, 4, 6, 8, 10]); // 4
|
|
1436
|
+
*
|
|
1437
|
+
* // SAFE: Limit both sequences
|
|
1438
|
+
* await asyncIter(largeAsyncDataset1).take(10000).covariance(
|
|
1439
|
+
* await asyncIter(largeAsyncDataset2).take(10000).toArray()
|
|
1440
|
+
* );
|
|
1441
|
+
*
|
|
1442
|
+
* // UNSAFE: Large datasets may cause memory issues
|
|
1443
|
+
* await asyncIter(millionRecords1).covariance(millionRecords2); // Materializes both!
|
|
1444
|
+
*
|
|
1445
|
+
* // SAFE: Process in windows
|
|
1446
|
+
* await asyncIter(largeAsyncDataset1)
|
|
1447
|
+
* .window(1000)
|
|
1448
|
+
* .map(async (window, i) =>
|
|
1449
|
+
* await asyncIter(window).covariance(
|
|
1450
|
+
* await asyncIter(largeAsyncDataset2).drop(i * 1000).take(1000).toArray()
|
|
1451
|
+
* )
|
|
1452
|
+
* )
|
|
1453
|
+
* .toArray();
|
|
1203
1454
|
* ```
|
|
1204
1455
|
*/
|
|
1205
1456
|
covariance(this: Asynciterflow<number>, other: AsyncIterable<number> | Iterable<number>): Promise<number | undefined>;
|
|
@@ -1207,12 +1458,33 @@ declare class Asynciterflow<T> implements AsyncIterable<T> {
|
|
|
1207
1458
|
* Calculates the Pearson correlation coefficient between two numeric sequences.
|
|
1208
1459
|
* This is a terminal operation that consumes the async iterator.
|
|
1209
1460
|
*
|
|
1461
|
+
* WARNING - Memory Intensive: This operation eagerly materializes both async iterators into memory
|
|
1462
|
+
* to calculate correlation. For large datasets, this doubles memory usage.
|
|
1463
|
+
*
|
|
1210
1464
|
* @param this - async iterflow instance constrained to numbers
|
|
1211
1465
|
* @param other - An async iterable of numbers to compare with
|
|
1212
1466
|
* @returns A promise of the correlation coefficient, or undefined if sequences are empty or have different lengths
|
|
1213
1467
|
* @example
|
|
1214
1468
|
* ```typescript
|
|
1469
|
+
* // SAFE: Small datasets
|
|
1215
1470
|
* await asyncIter([1, 2, 3, 4, 5]).correlation([2, 4, 6, 8, 10]); // 1
|
|
1471
|
+
*
|
|
1472
|
+
* // SAFE: Limit both sequences
|
|
1473
|
+
* await asyncIter(largeAsyncDataset1).take(10000).correlation(
|
|
1474
|
+
* await asyncIter(largeAsyncDataset2).take(10000).toArray()
|
|
1475
|
+
* );
|
|
1476
|
+
*
|
|
1477
|
+
* // UNSAFE: Large datasets may cause memory issues
|
|
1478
|
+
* await asyncIter(millionRecords1).correlation(millionRecords2); // Materializes both!
|
|
1479
|
+
*
|
|
1480
|
+
* // SAFE: Sample for approximate correlation
|
|
1481
|
+
* await asyncIter(largeAsyncDataset1)
|
|
1482
|
+
* .filter(async () => Math.random() < 0.01)
|
|
1483
|
+
* .correlation(
|
|
1484
|
+
* await asyncIter(largeAsyncDataset2)
|
|
1485
|
+
* .filter(async () => Math.random() < 0.01)
|
|
1486
|
+
* .toArray()
|
|
1487
|
+
* );
|
|
1216
1488
|
* ```
|
|
1217
1489
|
*/
|
|
1218
1490
|
correlation(this: Asynciterflow<number>, other: AsyncIterable<number> | Iterable<number>): Promise<number | undefined>;
|
|
@@ -1848,6 +2120,18 @@ declare namespace asyncIter {
|
|
|
1848
2120
|
*/
|
|
1849
2121
|
/**
|
|
1850
2122
|
* Base error class for all iterflow errors
|
|
2123
|
+
*
|
|
2124
|
+
* Provides a foundation for all library-specific errors with additional context
|
|
2125
|
+
* including the operation name and custom metadata for debugging.
|
|
2126
|
+
*
|
|
2127
|
+
* @example
|
|
2128
|
+
* ```typescript
|
|
2129
|
+
* throw new iterflowError(
|
|
2130
|
+
* "Invalid configuration",
|
|
2131
|
+
* "setupStream",
|
|
2132
|
+
* { config: { timeout: -1 } }
|
|
2133
|
+
* );
|
|
2134
|
+
* ```
|
|
1851
2135
|
*/
|
|
1852
2136
|
declare class iterflowError extends Error {
|
|
1853
2137
|
readonly operation?: string;
|
|
@@ -1855,31 +2139,135 @@ declare class iterflowError extends Error {
|
|
|
1855
2139
|
constructor(message: string, operation?: string, context?: Record<string, unknown>);
|
|
1856
2140
|
/**
|
|
1857
2141
|
* Returns a detailed error message with context
|
|
2142
|
+
*
|
|
2143
|
+
* Formats the error as a multi-line string including operation name, context data,
|
|
2144
|
+
* and stack trace for comprehensive debugging information.
|
|
2145
|
+
*
|
|
2146
|
+
* @returns A formatted string containing all error details
|
|
2147
|
+
* @example
|
|
2148
|
+
* ```typescript
|
|
2149
|
+
* const error = new iterflowError(
|
|
2150
|
+
* "Processing failed",
|
|
2151
|
+
* "transform",
|
|
2152
|
+
* { index: 42, value: null }
|
|
2153
|
+
* );
|
|
2154
|
+
* console.log(error.toDetailedString());
|
|
2155
|
+
* // iterflowError: Processing failed
|
|
2156
|
+
* // Operation: transform
|
|
2157
|
+
* // Context:
|
|
2158
|
+
* // index: 42
|
|
2159
|
+
* // value: null
|
|
2160
|
+
* // Stack: ...
|
|
2161
|
+
* ```
|
|
1858
2162
|
*/
|
|
1859
2163
|
toDetailedString(): string;
|
|
1860
2164
|
}
|
|
1861
2165
|
/**
|
|
1862
2166
|
* Error thrown when operation parameters are invalid
|
|
2167
|
+
*
|
|
2168
|
+
* Indicates that input validation failed due to incorrect parameter types,
|
|
2169
|
+
* out-of-range values, or other constraint violations.
|
|
2170
|
+
*
|
|
2171
|
+
* @example
|
|
2172
|
+
* ```typescript
|
|
2173
|
+
* // Thrown when validating a negative value that must be positive
|
|
2174
|
+
* throw new ValidationError(
|
|
2175
|
+
* "count must be positive, got -5",
|
|
2176
|
+
* "take",
|
|
2177
|
+
* { paramName: "count", value: -5 }
|
|
2178
|
+
* );
|
|
2179
|
+
* ```
|
|
1863
2180
|
*/
|
|
1864
2181
|
declare class ValidationError extends iterflowError {
|
|
1865
2182
|
constructor(message: string, operation?: string, context?: Record<string, unknown>);
|
|
1866
2183
|
}
|
|
1867
2184
|
/**
|
|
1868
2185
|
* Error thrown when an operation fails during execution
|
|
2186
|
+
*
|
|
2187
|
+
* Wraps underlying errors that occur during stream processing or transformations,
|
|
2188
|
+
* preserving the original error as the cause while adding operation context.
|
|
2189
|
+
*
|
|
2190
|
+
* @example
|
|
2191
|
+
* ```typescript
|
|
2192
|
+
* try {
|
|
2193
|
+
* await processItem(item);
|
|
2194
|
+
* } catch (error) {
|
|
2195
|
+
* throw new OperationError(
|
|
2196
|
+
* "Failed to process item",
|
|
2197
|
+
* "map",
|
|
2198
|
+
* error as Error,
|
|
2199
|
+
* { item, index: 5 }
|
|
2200
|
+
* );
|
|
2201
|
+
* }
|
|
2202
|
+
* ```
|
|
1869
2203
|
*/
|
|
1870
2204
|
declare class OperationError extends iterflowError {
|
|
1871
2205
|
readonly cause?: Error;
|
|
1872
2206
|
constructor(message: string, operation?: string, cause?: Error, context?: Record<string, unknown>);
|
|
2207
|
+
/**
|
|
2208
|
+
* Returns a detailed error message including the original cause
|
|
2209
|
+
*
|
|
2210
|
+
* Extends the base toDetailedString() to include information about the
|
|
2211
|
+
* underlying error that caused this operation to fail.
|
|
2212
|
+
*
|
|
2213
|
+
* @returns A formatted string with operation details and cause information
|
|
2214
|
+
* @example
|
|
2215
|
+
* ```typescript
|
|
2216
|
+
* const originalError = new Error("Network timeout");
|
|
2217
|
+
* const opError = new OperationError(
|
|
2218
|
+
* "Failed to fetch data",
|
|
2219
|
+
* "fetchAsync",
|
|
2220
|
+
* originalError
|
|
2221
|
+
* );
|
|
2222
|
+
* console.log(opError.toDetailedString());
|
|
2223
|
+
* // OperationError: Failed to fetch data
|
|
2224
|
+
* // Operation: fetchAsync
|
|
2225
|
+
* // Caused by: Network timeout
|
|
2226
|
+
* // [stack traces...]
|
|
2227
|
+
* ```
|
|
2228
|
+
*/
|
|
1873
2229
|
toDetailedString(): string;
|
|
1874
2230
|
}
|
|
1875
2231
|
/**
|
|
1876
2232
|
* Error thrown when an operation requires a non-empty sequence
|
|
2233
|
+
*
|
|
2234
|
+
* Indicates that an operation like first(), last(), or min() was called on an
|
|
2235
|
+
* empty iterable where at least one element is required to produce a result.
|
|
2236
|
+
*
|
|
2237
|
+
* @example
|
|
2238
|
+
* ```typescript
|
|
2239
|
+
* import { from } from 'iterflow';
|
|
2240
|
+
*
|
|
2241
|
+
* const empty = from([]);
|
|
2242
|
+
* try {
|
|
2243
|
+
* empty.first(); // Throws EmptySequenceError
|
|
2244
|
+
* } catch (error) {
|
|
2245
|
+
* console.error(error.message);
|
|
2246
|
+
* // "Operation 'first' requires a non-empty sequence"
|
|
2247
|
+
* }
|
|
2248
|
+
* ```
|
|
1877
2249
|
*/
|
|
1878
2250
|
declare class EmptySequenceError extends iterflowError {
|
|
1879
2251
|
constructor(operation: string, message?: string);
|
|
1880
2252
|
}
|
|
1881
2253
|
/**
|
|
1882
2254
|
* Error thrown when accessing an invalid index
|
|
2255
|
+
*
|
|
2256
|
+
* Indicates that an index-based operation attempted to access an element
|
|
2257
|
+
* outside the valid range of the collection (negative index or index >= size).
|
|
2258
|
+
*
|
|
2259
|
+
* @example
|
|
2260
|
+
* ```typescript
|
|
2261
|
+
* import { from } from 'iterflow';
|
|
2262
|
+
*
|
|
2263
|
+
* const items = from([1, 2, 3]);
|
|
2264
|
+
* try {
|
|
2265
|
+
* items.elementAt(10); // Only 3 elements, index 10 is out of bounds
|
|
2266
|
+
* } catch (error) {
|
|
2267
|
+
* console.error(error.message);
|
|
2268
|
+
* // "Index 10 is out of bounds (size: 3)"
|
|
2269
|
+
* }
|
|
2270
|
+
* ```
|
|
1883
2271
|
*/
|
|
1884
2272
|
declare class IndexOutOfBoundsError extends iterflowError {
|
|
1885
2273
|
readonly index: number;
|
|
@@ -1888,6 +2276,21 @@ declare class IndexOutOfBoundsError extends iterflowError {
|
|
|
1888
2276
|
}
|
|
1889
2277
|
/**
|
|
1890
2278
|
* Error thrown when a type conversion or coercion fails
|
|
2279
|
+
*
|
|
2280
|
+
* Indicates that an attempt to convert a value to a specific type failed,
|
|
2281
|
+
* such as converting a non-numeric string to a number or a decimal to an integer.
|
|
2282
|
+
*
|
|
2283
|
+
* @example
|
|
2284
|
+
* ```typescript
|
|
2285
|
+
* import { toNumber } from 'iterflow';
|
|
2286
|
+
*
|
|
2287
|
+
* try {
|
|
2288
|
+
* const num = toNumber("not-a-number");
|
|
2289
|
+
* } catch (error) {
|
|
2290
|
+
* console.error(error.message);
|
|
2291
|
+
* // 'Cannot convert value "not-a-number" to type number'
|
|
2292
|
+
* }
|
|
2293
|
+
* ```
|
|
1891
2294
|
*/
|
|
1892
2295
|
declare class TypeConversionError extends iterflowError {
|
|
1893
2296
|
readonly value: unknown;
|
|
@@ -1896,6 +2299,28 @@ declare class TypeConversionError extends iterflowError {
|
|
|
1896
2299
|
}
|
|
1897
2300
|
/**
|
|
1898
2301
|
* Error thrown when an operation exceeds its timeout duration
|
|
2302
|
+
*
|
|
2303
|
+
* Indicates that an async operation took longer than the specified timeout
|
|
2304
|
+
* and was terminated to prevent indefinite waiting.
|
|
2305
|
+
*
|
|
2306
|
+
* @example
|
|
2307
|
+
* ```typescript
|
|
2308
|
+
* import { fromAsync } from 'iterflow';
|
|
2309
|
+
*
|
|
2310
|
+
* async function* slowGenerator() {
|
|
2311
|
+
* yield await new Promise(resolve => setTimeout(() => resolve(1), 5000));
|
|
2312
|
+
* }
|
|
2313
|
+
*
|
|
2314
|
+
* try {
|
|
2315
|
+
* // Timeout after 1 second
|
|
2316
|
+
* await fromAsync(slowGenerator())
|
|
2317
|
+
* .withTimeout(1000)
|
|
2318
|
+
* .toArray();
|
|
2319
|
+
* } catch (error) {
|
|
2320
|
+
* console.error(error.message);
|
|
2321
|
+
* // "Operation timed out after 1000ms"
|
|
2322
|
+
* }
|
|
2323
|
+
* ```
|
|
1899
2324
|
*/
|
|
1900
2325
|
declare class TimeoutError extends iterflowError {
|
|
1901
2326
|
readonly timeoutMs: number;
|
|
@@ -1903,6 +2328,27 @@ declare class TimeoutError extends iterflowError {
|
|
|
1903
2328
|
}
|
|
1904
2329
|
/**
|
|
1905
2330
|
* Error thrown when an operation is aborted via AbortSignal
|
|
2331
|
+
*
|
|
2332
|
+
* Indicates that an async operation was cancelled using an AbortController,
|
|
2333
|
+
* typically for user-initiated cancellation or cleanup during component unmounting.
|
|
2334
|
+
*
|
|
2335
|
+
* @example
|
|
2336
|
+
* ```typescript
|
|
2337
|
+
* import { fromAsync } from 'iterflow';
|
|
2338
|
+
*
|
|
2339
|
+
* const controller = new AbortController();
|
|
2340
|
+
*
|
|
2341
|
+
* setTimeout(() => controller.abort("User cancelled"), 1000);
|
|
2342
|
+
*
|
|
2343
|
+
* try {
|
|
2344
|
+
* await fromAsync(longRunningGenerator())
|
|
2345
|
+
* .withAbortSignal(controller.signal)
|
|
2346
|
+
* .toArray();
|
|
2347
|
+
* } catch (error) {
|
|
2348
|
+
* console.error(error.message);
|
|
2349
|
+
* // "Operation aborted: User cancelled"
|
|
2350
|
+
* }
|
|
2351
|
+
* ```
|
|
1906
2352
|
*/
|
|
1907
2353
|
declare class AbortError extends iterflowError {
|
|
1908
2354
|
readonly reason?: string;
|
|
@@ -1918,47 +2364,246 @@ declare class AbortError extends iterflowError {
|
|
|
1918
2364
|
*/
|
|
1919
2365
|
declare function validatePositiveInteger(value: number, paramName: string, operation?: string): void;
|
|
1920
2366
|
/**
|
|
1921
|
-
* Validates that a value is a non-negative integer
|
|
2367
|
+
* Validates that a value is a non-negative integer (zero or greater)
|
|
2368
|
+
*
|
|
2369
|
+
* This function ensures the value is both an integer and non-negative, making it
|
|
2370
|
+
* suitable for array indices, counts, and offsets that can start from zero.
|
|
2371
|
+
*
|
|
2372
|
+
* @param value - The value to validate
|
|
2373
|
+
* @param paramName - The parameter name for error messages
|
|
2374
|
+
* @param operation - The operation name for error context
|
|
2375
|
+
* @throws {ValidationError} When value is not an integer
|
|
2376
|
+
* @throws {ValidationError} When value is negative
|
|
2377
|
+
* @example
|
|
2378
|
+
* ```typescript
|
|
2379
|
+
* validateNonNegativeInteger(0, "index"); // OK - zero is allowed
|
|
2380
|
+
* validateNonNegativeInteger(5, "offset"); // OK
|
|
2381
|
+
* validateNonNegativeInteger(-1, "index"); // throws ValidationError
|
|
2382
|
+
* validateNonNegativeInteger(1.5, "count"); // throws ValidationError
|
|
2383
|
+
* ```
|
|
1922
2384
|
*/
|
|
1923
2385
|
declare function validateNonNegativeInteger(value: number, paramName: string, operation?: string): void;
|
|
1924
2386
|
/**
|
|
1925
|
-
* Validates that a value is within a specific range
|
|
2387
|
+
* Validates that a value is within a specific range (inclusive)
|
|
2388
|
+
*
|
|
2389
|
+
* Checks that a numeric value falls within the specified bounds, including
|
|
2390
|
+
* both minimum and maximum values. Useful for percentages, bounded parameters,
|
|
2391
|
+
* and range-constrained inputs.
|
|
2392
|
+
*
|
|
2393
|
+
* @param value - The value to validate
|
|
2394
|
+
* @param min - The minimum allowed value (inclusive)
|
|
2395
|
+
* @param max - The maximum allowed value (inclusive)
|
|
2396
|
+
* @param paramName - The parameter name for error messages
|
|
2397
|
+
* @param operation - The operation name for error context
|
|
2398
|
+
* @throws {ValidationError} When value is less than min or greater than max
|
|
2399
|
+
* @example
|
|
2400
|
+
* ```typescript
|
|
2401
|
+
* validateRange(50, 0, 100, "percent"); // OK
|
|
2402
|
+
* validateRange(0, 0, 100, "percent"); // OK - min boundary
|
|
2403
|
+
* validateRange(100, 0, 100, "percent"); // OK - max boundary
|
|
2404
|
+
* validateRange(150, 0, 100, "percent"); // throws ValidationError
|
|
2405
|
+
* validateRange(-10, 0, 100, "percent"); // throws ValidationError
|
|
2406
|
+
* ```
|
|
1926
2407
|
*/
|
|
1927
2408
|
declare function validateRange(value: number, min: number, max: number, paramName: string, operation?: string): void;
|
|
1928
2409
|
/**
|
|
1929
2410
|
* Validates that a value is a finite number (not NaN or Infinity)
|
|
2411
|
+
*
|
|
2412
|
+
* Ensures the value is a real, finite number that can be used in mathematical
|
|
2413
|
+
* operations. Rejects NaN, Infinity, and -Infinity which could cause undefined
|
|
2414
|
+
* behavior in calculations.
|
|
2415
|
+
*
|
|
2416
|
+
* @param value - The value to validate
|
|
2417
|
+
* @param paramName - The parameter name for error messages
|
|
2418
|
+
* @param operation - The operation name for error context
|
|
2419
|
+
* @throws {ValidationError} When value is NaN, Infinity, or -Infinity
|
|
2420
|
+
* @example
|
|
2421
|
+
* ```typescript
|
|
2422
|
+
* validateFiniteNumber(42, "weight"); // OK
|
|
2423
|
+
* validateFiniteNumber(-3.14, "temperature"); // OK
|
|
2424
|
+
* validateFiniteNumber(0, "value"); // OK
|
|
2425
|
+
* validateFiniteNumber(NaN, "result"); // throws ValidationError
|
|
2426
|
+
* validateFiniteNumber(Infinity, "max"); // throws ValidationError
|
|
2427
|
+
* ```
|
|
1930
2428
|
*/
|
|
1931
2429
|
declare function validateFiniteNumber(value: number, paramName: string, operation?: string): void;
|
|
1932
2430
|
/**
|
|
1933
2431
|
* Validates that a value is not zero
|
|
2432
|
+
*
|
|
2433
|
+
* Prevents division by zero errors and other operations where zero is invalid.
|
|
2434
|
+
* Detects both positive and negative zero.
|
|
2435
|
+
*
|
|
2436
|
+
* @param value - The value to validate
|
|
2437
|
+
* @param paramName - The parameter name for error messages
|
|
2438
|
+
* @param operation - The operation name for error context
|
|
2439
|
+
* @throws {ValidationError} When value equals zero (including -0)
|
|
2440
|
+
* @example
|
|
2441
|
+
* ```typescript
|
|
2442
|
+
* validateNonZero(1, "divisor"); // OK
|
|
2443
|
+
* validateNonZero(-5, "denominator"); // OK
|
|
2444
|
+
* validateNonZero(0.1, "scale"); // OK
|
|
2445
|
+
* validateNonZero(0, "divisor"); // throws ValidationError
|
|
2446
|
+
* validateNonZero(-0, "divisor"); // throws ValidationError
|
|
2447
|
+
* ```
|
|
1934
2448
|
*/
|
|
1935
2449
|
declare function validateNonZero(value: number, paramName: string, operation?: string): void;
|
|
1936
2450
|
/**
|
|
1937
2451
|
* Validates that a value is a function
|
|
2452
|
+
*
|
|
2453
|
+
* Type guard that ensures the value is callable. Accepts arrow functions, regular
|
|
2454
|
+
* functions, async functions, generator functions, and class constructors.
|
|
2455
|
+
* Uses TypeScript assertion to narrow the type.
|
|
2456
|
+
*
|
|
2457
|
+
* @param value - The value to validate
|
|
2458
|
+
* @param paramName - The parameter name for error messages
|
|
2459
|
+
* @param operation - The operation name for error context
|
|
2460
|
+
* @throws {ValidationError} When value is not a function
|
|
2461
|
+
* @example
|
|
2462
|
+
* ```typescript
|
|
2463
|
+
* validateFunction((x) => x * 2, "mapper"); // OK
|
|
2464
|
+
* validateFunction(Math.max, "comparator"); // OK
|
|
2465
|
+
* async function fetch() {}
|
|
2466
|
+
* validateFunction(fetch, "loader"); // OK
|
|
2467
|
+
* validateFunction(null, "callback"); // throws ValidationError
|
|
2468
|
+
* validateFunction("not a function", "fn"); // throws ValidationError
|
|
2469
|
+
* ```
|
|
1938
2470
|
*/
|
|
1939
|
-
declare function validateFunction(value: unknown, paramName: string, operation?: string): asserts value is
|
|
2471
|
+
declare function validateFunction(value: unknown, paramName: string, operation?: string): asserts value is (...args: unknown[]) => unknown;
|
|
1940
2472
|
/**
|
|
1941
2473
|
* Validates that a value is iterable
|
|
2474
|
+
*
|
|
2475
|
+
* Type guard ensuring the value implements the iterable protocol (has Symbol.iterator).
|
|
2476
|
+
* Accepts arrays, strings, Maps, Sets, generators, and custom iterables.
|
|
2477
|
+
* Uses TypeScript assertion to narrow the type.
|
|
2478
|
+
*
|
|
2479
|
+
* @param value - The value to validate
|
|
2480
|
+
* @param paramName - The parameter name for error messages
|
|
2481
|
+
* @param operation - The operation name for error context
|
|
2482
|
+
* @throws {ValidationError} When value is null, undefined, or lacks Symbol.iterator
|
|
2483
|
+
* @example
|
|
2484
|
+
* ```typescript
|
|
2485
|
+
* validateIterable([1, 2, 3], "items"); // OK
|
|
2486
|
+
* validateIterable("hello", "text"); // OK
|
|
2487
|
+
* validateIterable(new Set([1, 2]), "uniqueIds"); // OK
|
|
2488
|
+
* function* gen() { yield 1; }
|
|
2489
|
+
* validateIterable(gen(), "sequence"); // OK
|
|
2490
|
+
* validateIterable(null, "items"); // throws ValidationError
|
|
2491
|
+
* validateIterable({ a: 1 }, "obj"); // throws ValidationError
|
|
2492
|
+
* ```
|
|
1942
2493
|
*/
|
|
1943
2494
|
declare function validateIterable<T>(value: unknown, paramName: string, operation?: string): asserts value is Iterable<T>;
|
|
1944
2495
|
/**
|
|
1945
2496
|
* Validates that a value is a valid comparator function
|
|
2497
|
+
*
|
|
2498
|
+
* Type guard ensuring the value is a function suitable for sorting and comparison
|
|
2499
|
+
* operations. A comparator should return a negative number if a < b, zero if a === b,
|
|
2500
|
+
* and a positive number if a > b. Uses TypeScript assertion to narrow the type.
|
|
2501
|
+
*
|
|
2502
|
+
* @param fn - The value to validate as a comparator
|
|
2503
|
+
* @param operation - The operation name for error context
|
|
2504
|
+
* @throws {ValidationError} When fn is not a function
|
|
2505
|
+
* @example
|
|
2506
|
+
* ```typescript
|
|
2507
|
+
* const numCompare = (a: number, b: number) => a - b;
|
|
2508
|
+
* validateComparator(numCompare); // OK
|
|
2509
|
+
*
|
|
2510
|
+
* const strCompare = (a: string, b: string) => a.localeCompare(b);
|
|
2511
|
+
* validateComparator(strCompare, "sortBy"); // OK
|
|
2512
|
+
*
|
|
2513
|
+
* validateComparator(null, "sort"); // throws ValidationError
|
|
2514
|
+
* validateComparator("not a function", "sort"); // throws ValidationError
|
|
2515
|
+
* ```
|
|
1946
2516
|
*/
|
|
1947
2517
|
declare function validateComparator<T>(fn: unknown, operation?: string): asserts fn is (a: T, b: T) => number;
|
|
1948
2518
|
/**
|
|
1949
2519
|
* Validates that an array is not empty
|
|
2520
|
+
*
|
|
2521
|
+
* Ensures an array has at least one element. Useful for operations that require
|
|
2522
|
+
* at least one item to function properly (e.g., finding min/max, first/last).
|
|
2523
|
+
*
|
|
2524
|
+
* @param arr - The array to validate
|
|
2525
|
+
* @param operation - The operation name for error context
|
|
2526
|
+
* @throws {ValidationError} When the array is empty (length === 0)
|
|
2527
|
+
* @example
|
|
2528
|
+
* ```typescript
|
|
2529
|
+
* validateNonEmpty([1, 2, 3]); // OK
|
|
2530
|
+
* validateNonEmpty(["a"]); // OK
|
|
2531
|
+
* validateNonEmpty([]); // throws ValidationError
|
|
2532
|
+
*
|
|
2533
|
+
* // Usage in operations requiring elements
|
|
2534
|
+
* function findMax(arr: number[]): number {
|
|
2535
|
+
* validateNonEmpty(arr, "findMax");
|
|
2536
|
+
* return Math.max(...arr);
|
|
2537
|
+
* }
|
|
2538
|
+
* ```
|
|
1950
2539
|
*/
|
|
1951
2540
|
declare function validateNonEmpty<T>(arr: T[], operation?: string): void;
|
|
1952
2541
|
/**
|
|
1953
2542
|
* Safely converts a value to a number
|
|
2543
|
+
*
|
|
2544
|
+
* Attempts to convert any value to a number using JavaScript's Number() constructor.
|
|
2545
|
+
* Throws a specific error if the conversion results in NaN, providing clear feedback
|
|
2546
|
+
* about type conversion failures.
|
|
2547
|
+
*
|
|
2548
|
+
* @param value - The value to convert to a number
|
|
2549
|
+
* @param operation - The operation name for error context
|
|
2550
|
+
* @returns The numeric representation of the value
|
|
2551
|
+
* @throws {TypeConversionError} When conversion results in NaN
|
|
2552
|
+
* @example
|
|
2553
|
+
* ```typescript
|
|
2554
|
+
* toNumber("123"); // returns 123
|
|
2555
|
+
* toNumber("45.6"); // returns 45.6
|
|
2556
|
+
* toNumber(100); // returns 100
|
|
2557
|
+
* toNumber(true); // returns 1
|
|
2558
|
+
* toNumber("not a number"); // throws TypeConversionError
|
|
2559
|
+
* toNumber(undefined); // throws TypeConversionError
|
|
2560
|
+
* ```
|
|
1954
2561
|
*/
|
|
1955
2562
|
declare function toNumber(value: unknown, operation?: string): number;
|
|
1956
2563
|
/**
|
|
1957
2564
|
* Safely converts a value to an integer
|
|
2565
|
+
*
|
|
2566
|
+
* Converts a value to a number and ensures it's an integer (no decimal part).
|
|
2567
|
+
* Uses Math.trunc to identify the integer portion and validates that no precision
|
|
2568
|
+
* is lost during conversion.
|
|
2569
|
+
*
|
|
2570
|
+
* @param value - The value to convert to an integer
|
|
2571
|
+
* @param operation - The operation name for error context
|
|
2572
|
+
* @returns The integer representation of the value
|
|
2573
|
+
* @throws {TypeConversionError} When conversion to number fails (NaN)
|
|
2574
|
+
* @throws {TypeConversionError} When the number has a fractional part
|
|
2575
|
+
* @example
|
|
2576
|
+
* ```typescript
|
|
2577
|
+
* toInteger("123"); // returns 123
|
|
2578
|
+
* toInteger(456); // returns 456
|
|
2579
|
+
* toInteger("0"); // returns 0
|
|
2580
|
+
* toInteger("-50"); // returns -50
|
|
2581
|
+
* toInteger("123.45"); // throws TypeConversionError
|
|
2582
|
+
* toInteger(789.12); // throws TypeConversionError
|
|
2583
|
+
* toInteger("abc"); // throws TypeConversionError
|
|
2584
|
+
* ```
|
|
1958
2585
|
*/
|
|
1959
2586
|
declare function toInteger(value: unknown, operation?: string): number;
|
|
1960
2587
|
/**
|
|
1961
|
-
* Validates array index
|
|
2588
|
+
* Validates an array index is within bounds
|
|
2589
|
+
*
|
|
2590
|
+
* Ensures an index is a non-negative integer and falls within the valid range
|
|
2591
|
+
* for an array or collection of the given size. Valid indices are 0 to size-1.
|
|
2592
|
+
*
|
|
2593
|
+
* @param index - The index to validate
|
|
2594
|
+
* @param size - The size of the array or collection
|
|
2595
|
+
* @param operation - The operation name for error context
|
|
2596
|
+
* @throws {ValidationError} When index is not a non-negative integer
|
|
2597
|
+
* @throws {ValidationError} When index is greater than or equal to size
|
|
2598
|
+
* @example
|
|
2599
|
+
* ```typescript
|
|
2600
|
+
* validateIndex(0, 10); // OK
|
|
2601
|
+
* validateIndex(5, 10); // OK
|
|
2602
|
+
* validateIndex(9, 10); // OK - last valid index
|
|
2603
|
+
* validateIndex(10, 10); // throws ValidationError - out of bounds
|
|
2604
|
+
* validateIndex(-1, 10); // throws ValidationError - negative
|
|
2605
|
+
* validateIndex(1.5, 10); // throws ValidationError - not integer
|
|
2606
|
+
* ```
|
|
1962
2607
|
*/
|
|
1963
2608
|
declare function validateIndex(index: number, size: number, operation?: string): void;
|
|
1964
2609
|
|
|
@@ -2007,22 +2652,120 @@ declare function isDebugEnabled(): boolean;
|
|
|
2007
2652
|
declare function getDebugConfig(): Readonly<DebugConfig>;
|
|
2008
2653
|
/**
|
|
2009
2654
|
* Add a trace entry
|
|
2655
|
+
*
|
|
2656
|
+
* Manually records an operation trace entry for debugging purposes.
|
|
2657
|
+
* Traces are only recorded when debug mode is enabled with traceOperations: true.
|
|
2658
|
+
*
|
|
2659
|
+
* @param entry - The trace entry to add
|
|
2660
|
+
* @example
|
|
2661
|
+
* ```typescript
|
|
2662
|
+
* import { enableDebug, addTrace } from 'iterflow';
|
|
2663
|
+
*
|
|
2664
|
+
* enableDebug({ traceOperations: true });
|
|
2665
|
+
*
|
|
2666
|
+
* addTrace({
|
|
2667
|
+
* operation: 'customOp',
|
|
2668
|
+
* timestamp: Date.now(),
|
|
2669
|
+
* duration: 42.5,
|
|
2670
|
+
* metadata: { itemsProcessed: 100 }
|
|
2671
|
+
* });
|
|
2672
|
+
* ```
|
|
2010
2673
|
*/
|
|
2011
2674
|
declare function addTrace(entry: TraceEntry): void;
|
|
2012
2675
|
/**
|
|
2013
2676
|
* Get all trace entries
|
|
2677
|
+
*
|
|
2678
|
+
* Retrieves all recorded trace entries for analysis. Each trace entry contains
|
|
2679
|
+
* operation name, timestamp, duration, and optional input/output/error data.
|
|
2680
|
+
*
|
|
2681
|
+
* @returns An immutable array of all trace entries
|
|
2682
|
+
* @example
|
|
2683
|
+
* ```typescript
|
|
2684
|
+
* import { from, enableDebug, getTraces } from 'iterflow';
|
|
2685
|
+
*
|
|
2686
|
+
* enableDebug({ traceOperations: true, traceInput: true, traceOutput: true });
|
|
2687
|
+
*
|
|
2688
|
+
* from([1, 2, 3]).map(x => x * 2).toArray();
|
|
2689
|
+
*
|
|
2690
|
+
* const traces = getTraces();
|
|
2691
|
+
* traces.forEach(trace => {
|
|
2692
|
+
* console.log(`${trace.operation} took ${trace.duration}ms`);
|
|
2693
|
+
* });
|
|
2694
|
+
* ```
|
|
2014
2695
|
*/
|
|
2015
2696
|
declare function getTraces(): readonly TraceEntry[];
|
|
2016
2697
|
/**
|
|
2017
2698
|
* Clear all traces
|
|
2699
|
+
*
|
|
2700
|
+
* Removes all recorded trace entries from memory. Useful for resetting debug state
|
|
2701
|
+
* between test runs or freeing memory after analyzing traces.
|
|
2702
|
+
*
|
|
2703
|
+
* @example
|
|
2704
|
+
* ```typescript
|
|
2705
|
+
* import { enableDebug, getTraces, clearTraces } from 'iterflow';
|
|
2706
|
+
*
|
|
2707
|
+
* enableDebug({ traceOperations: true });
|
|
2708
|
+
*
|
|
2709
|
+
* // ... run some operations ...
|
|
2710
|
+
*
|
|
2711
|
+
* const traces = getTraces();
|
|
2712
|
+
* analyzePerformance(traces);
|
|
2713
|
+
*
|
|
2714
|
+
* clearTraces(); // Reset for next benchmark
|
|
2715
|
+
* ```
|
|
2018
2716
|
*/
|
|
2019
2717
|
declare function clearTraces(): void;
|
|
2020
2718
|
/**
|
|
2021
2719
|
* Get traces for a specific operation
|
|
2720
|
+
*
|
|
2721
|
+
* Filters trace entries to return only those for the specified operation name.
|
|
2722
|
+
* Useful for analyzing performance of a specific method or transformation.
|
|
2723
|
+
*
|
|
2724
|
+
* @param operation - The operation name to filter by (e.g., "map", "filter")
|
|
2725
|
+
* @returns An array of trace entries for the specified operation
|
|
2726
|
+
* @example
|
|
2727
|
+
* ```typescript
|
|
2728
|
+
* import { from, enableDebug, getTracesForOperation } from 'iterflow';
|
|
2729
|
+
*
|
|
2730
|
+
* enableDebug({ traceOperations: true });
|
|
2731
|
+
*
|
|
2732
|
+
* from([1, 2, 3])
|
|
2733
|
+
* .map(x => x * 2)
|
|
2734
|
+
* .filter(x => x > 3)
|
|
2735
|
+
* .toArray();
|
|
2736
|
+
*
|
|
2737
|
+
* const mapTraces = getTracesForOperation('map');
|
|
2738
|
+
* console.log(`map was called ${mapTraces.length} times`);
|
|
2739
|
+
* ```
|
|
2022
2740
|
*/
|
|
2023
2741
|
declare function getTracesForOperation(operation: string): TraceEntry[];
|
|
2024
2742
|
/**
|
|
2025
2743
|
* Get trace summary statistics
|
|
2744
|
+
*
|
|
2745
|
+
* Computes aggregated statistics for each operation including call count,
|
|
2746
|
+
* average duration, and error count. Useful for identifying performance
|
|
2747
|
+
* bottlenecks and error-prone operations.
|
|
2748
|
+
*
|
|
2749
|
+
* @returns An object mapping operation names to their statistics
|
|
2750
|
+
* @example
|
|
2751
|
+
* ```typescript
|
|
2752
|
+
* import { from, enableDebug, getTraceSummary } from 'iterflow';
|
|
2753
|
+
*
|
|
2754
|
+
* enableDebug({ traceOperations: true });
|
|
2755
|
+
*
|
|
2756
|
+
* from([1, 2, 3, 4, 5])
|
|
2757
|
+
* .map(x => x * 2)
|
|
2758
|
+
* .filter(x => x > 5)
|
|
2759
|
+
* .toArray();
|
|
2760
|
+
*
|
|
2761
|
+
* const summary = getTraceSummary();
|
|
2762
|
+
* Object.entries(summary).forEach(([op, stats]) => {
|
|
2763
|
+
* console.log(`${op}: ${stats.count} calls, avg ${stats.avgDuration.toFixed(2)}ms`);
|
|
2764
|
+
* });
|
|
2765
|
+
* // Output:
|
|
2766
|
+
* // map: 5 calls, avg 0.02ms
|
|
2767
|
+
* // filter: 5 calls, avg 0.01ms
|
|
2768
|
+
* ```
|
|
2026
2769
|
*/
|
|
2027
2770
|
declare function getTraceSummary(): Record<string, {
|
|
2028
2771
|
count: number;
|
|
@@ -2031,10 +2774,59 @@ declare function getTraceSummary(): Record<string, {
|
|
|
2031
2774
|
}>;
|
|
2032
2775
|
/**
|
|
2033
2776
|
* Wrapper function to trace operation execution
|
|
2777
|
+
*
|
|
2778
|
+
* Wraps a synchronous function to automatically record execution timing and errors.
|
|
2779
|
+
* Only records traces when debug mode is enabled.
|
|
2780
|
+
*
|
|
2781
|
+
* @template T - The function's return type
|
|
2782
|
+
* @param operation - The operation name for the trace entry
|
|
2783
|
+
* @param fn - The function to execute and trace
|
|
2784
|
+
* @param metadata - Optional metadata to include in the trace entry
|
|
2785
|
+
* @returns The result of executing fn
|
|
2786
|
+
* @example
|
|
2787
|
+
* ```typescript
|
|
2788
|
+
* import { enableDebug, traceOperation } from 'iterflow';
|
|
2789
|
+
*
|
|
2790
|
+
* enableDebug({ traceOperations: true });
|
|
2791
|
+
*
|
|
2792
|
+
* const result = traceOperation(
|
|
2793
|
+
* 'computeExpensive',
|
|
2794
|
+
* () => {
|
|
2795
|
+
* let sum = 0;
|
|
2796
|
+
* for (let i = 0; i < 1000000; i++) sum += i;
|
|
2797
|
+
* return sum;
|
|
2798
|
+
* },
|
|
2799
|
+
* { iterations: 1000000 }
|
|
2800
|
+
* );
|
|
2801
|
+
* ```
|
|
2034
2802
|
*/
|
|
2035
2803
|
declare function traceOperation<T>(operation: string, fn: () => T, metadata?: Record<string, unknown>): T;
|
|
2036
2804
|
/**
|
|
2037
2805
|
* Async version of traceOperation
|
|
2806
|
+
*
|
|
2807
|
+
* Wraps an async function to automatically record execution timing and errors.
|
|
2808
|
+
* Only records traces when debug mode is enabled.
|
|
2809
|
+
*
|
|
2810
|
+
* @template T - The function's return type
|
|
2811
|
+
* @param operation - The operation name for the trace entry
|
|
2812
|
+
* @param fn - The async function to execute and trace
|
|
2813
|
+
* @param metadata - Optional metadata to include in the trace entry
|
|
2814
|
+
* @returns A promise resolving to the result of executing fn
|
|
2815
|
+
* @example
|
|
2816
|
+
* ```typescript
|
|
2817
|
+
* import { enableDebug, traceOperationAsync } from 'iterflow';
|
|
2818
|
+
*
|
|
2819
|
+
* enableDebug({ traceOperations: true });
|
|
2820
|
+
*
|
|
2821
|
+
* const data = await traceOperationAsync(
|
|
2822
|
+
* 'fetchUserData',
|
|
2823
|
+
* async () => {
|
|
2824
|
+
* const response = await fetch('/api/users');
|
|
2825
|
+
* return response.json();
|
|
2826
|
+
* },
|
|
2827
|
+
* { endpoint: '/api/users' }
|
|
2828
|
+
* );
|
|
2829
|
+
* ```
|
|
2038
2830
|
*/
|
|
2039
2831
|
declare function traceOperationAsync<T>(operation: string, fn: () => Promise<T>, metadata?: Record<string, unknown>): Promise<T>;
|
|
2040
2832
|
|
|
@@ -2061,26 +2853,168 @@ interface RetryOptions {
|
|
|
2061
2853
|
declare function withErrorRecovery<T, R>(fn: (value: T, index?: number) => R, errorHandler: ErrorHandler<T, R>): (value: T, index?: number) => R;
|
|
2062
2854
|
/**
|
|
2063
2855
|
* Wraps a function with retry logic
|
|
2856
|
+
*
|
|
2857
|
+
* Automatically retries a function on failure with configurable attempts, delays,
|
|
2858
|
+
* and exponential backoff. Useful for handling transient failures in operations
|
|
2859
|
+
* that may succeed on subsequent attempts.
|
|
2860
|
+
*
|
|
2861
|
+
* @template T - The function's argument types as a tuple
|
|
2862
|
+
* @template R - The function's return type
|
|
2863
|
+
* @param fn - The function to wrap with retry logic
|
|
2864
|
+
* @param options - Configuration object with maxAttempts (default: 3), delay in ms (default: 0), backoff flag (default: false), and optional onRetry callback
|
|
2865
|
+
* @returns A wrapped function that retries on failure
|
|
2866
|
+
* @throws {OperationError} When all retry attempts are exhausted
|
|
2867
|
+
* @example
|
|
2868
|
+
* ```typescript
|
|
2869
|
+
* const fetchWithRetry = withRetry(
|
|
2870
|
+
* () => fetch('/api/data').then(r => r.json()),
|
|
2871
|
+
* {
|
|
2872
|
+
* maxAttempts: 3,
|
|
2873
|
+
* delay: 1000,
|
|
2874
|
+
* backoff: true,
|
|
2875
|
+
* onRetry: (attempt, error) => console.log(`Retry ${attempt}: ${error.message}`)
|
|
2876
|
+
* }
|
|
2877
|
+
* );
|
|
2878
|
+
*
|
|
2879
|
+
* const data = fetchWithRetry();
|
|
2880
|
+
* ```
|
|
2064
2881
|
*/
|
|
2065
2882
|
declare function withRetry<T extends any[], R>(fn: (...args: T) => R, options?: RetryOptions): (...args: T) => R;
|
|
2066
2883
|
/**
|
|
2067
2884
|
* Async version of withRetry
|
|
2885
|
+
*
|
|
2886
|
+
* Wraps an async function with retry logic, using proper async delays instead of
|
|
2887
|
+
* busy-waiting. Ideal for network requests, database operations, or other async
|
|
2888
|
+
* operations that may fail transiently.
|
|
2889
|
+
*
|
|
2890
|
+
* @template T - The function's argument types as a tuple
|
|
2891
|
+
* @template R - The function's return type
|
|
2892
|
+
* @param fn - The async function to wrap with retry logic
|
|
2893
|
+
* @param options - Configuration object with maxAttempts (default: 3), delay in ms (default: 0), backoff flag (default: false), and optional onRetry callback
|
|
2894
|
+
* @returns A wrapped async function that retries on failure
|
|
2895
|
+
* @throws {OperationError} When all retry attempts are exhausted
|
|
2896
|
+
* @example
|
|
2897
|
+
* ```typescript
|
|
2898
|
+
* const fetchDataWithRetry = withRetryAsync(
|
|
2899
|
+
* async (id: string) => {
|
|
2900
|
+
* const response = await fetch(`/api/items/${id}`);
|
|
2901
|
+
* return response.json();
|
|
2902
|
+
* },
|
|
2903
|
+
* {
|
|
2904
|
+
* maxAttempts: 5,
|
|
2905
|
+
* delay: 500,
|
|
2906
|
+
* backoff: true
|
|
2907
|
+
* }
|
|
2908
|
+
* );
|
|
2909
|
+
*
|
|
2910
|
+
* const item = await fetchDataWithRetry('123');
|
|
2911
|
+
* ```
|
|
2068
2912
|
*/
|
|
2069
2913
|
declare function withRetryAsync<T extends any[], R>(fn: (...args: T) => Promise<R>, options?: RetryOptions): (...args: T) => Promise<R>;
|
|
2070
2914
|
/**
|
|
2071
2915
|
* Returns a default value if an error occurs
|
|
2916
|
+
*
|
|
2917
|
+
* Wraps a function to catch any errors and return a fallback value instead,
|
|
2918
|
+
* preventing exceptions from propagating. Useful for providing safe defaults
|
|
2919
|
+
* in transformations or mappings.
|
|
2920
|
+
*
|
|
2921
|
+
* @template T - The input value type
|
|
2922
|
+
* @template R - The return/default value type
|
|
2923
|
+
* @param fn - The function that may throw
|
|
2924
|
+
* @param defaultValue - The value to return if fn throws
|
|
2925
|
+
* @returns A wrapped function that returns defaultValue on error
|
|
2926
|
+
* @example
|
|
2927
|
+
* ```typescript
|
|
2928
|
+
* const parseIntSafe = withDefault(
|
|
2929
|
+
* (str: string) => {
|
|
2930
|
+
* const num = parseInt(str, 10);
|
|
2931
|
+
* if (isNaN(num)) throw new Error("Not a number");
|
|
2932
|
+
* return num;
|
|
2933
|
+
* },
|
|
2934
|
+
* 0
|
|
2935
|
+
* );
|
|
2936
|
+
*
|
|
2937
|
+
* parseIntSafe("123"); // returns 123
|
|
2938
|
+
* parseIntSafe("abc"); // returns 0 (default)
|
|
2939
|
+
* ```
|
|
2072
2940
|
*/
|
|
2073
2941
|
declare function withDefault<T, R>(fn: (value: T) => R, defaultValue: R): (value: T) => R;
|
|
2074
2942
|
/**
|
|
2075
|
-
* Returns
|
|
2943
|
+
* Returns a fallback value if an error occurs (swallows errors)
|
|
2944
|
+
*
|
|
2945
|
+
* Similar to withDefault, this function wraps another function and returns a fallback
|
|
2946
|
+
* value on error. Provides error-safe execution for operations that should never throw.
|
|
2947
|
+
*
|
|
2948
|
+
* @template T - The input value type
|
|
2949
|
+
* @template R - The return/fallback value type
|
|
2950
|
+
* @param fn - The function that may throw
|
|
2951
|
+
* @param fallback - The value to return if fn throws
|
|
2952
|
+
* @returns A wrapped function that returns fallback on error
|
|
2953
|
+
* @example
|
|
2954
|
+
* ```typescript
|
|
2955
|
+
* const safeDivide = tryOr(
|
|
2956
|
+
* (x: number) => 100 / x,
|
|
2957
|
+
* Infinity
|
|
2958
|
+
* );
|
|
2959
|
+
*
|
|
2960
|
+
* safeDivide(10); // returns 10
|
|
2961
|
+
* safeDivide(0); // returns Infinity (fallback)
|
|
2962
|
+
* ```
|
|
2076
2963
|
*/
|
|
2077
2964
|
declare function tryOr<T, R>(fn: (value: T) => R, fallback: R): (value: T) => R;
|
|
2078
2965
|
/**
|
|
2079
2966
|
* Executes a function and returns [result, error] tuple
|
|
2967
|
+
*
|
|
2968
|
+
* Provides Go-style error handling by returning both the result and error as a tuple.
|
|
2969
|
+
* Allows explicit error handling without try-catch blocks.
|
|
2970
|
+
*
|
|
2971
|
+
* @template T - The input value type
|
|
2972
|
+
* @template R - The function's return type
|
|
2973
|
+
* @param fn - The function to execute
|
|
2974
|
+
* @param value - The value to pass to fn
|
|
2975
|
+
* @returns A tuple of [result, undefined] on success or [undefined, error] on failure
|
|
2976
|
+
* @example
|
|
2977
|
+
* ```typescript
|
|
2978
|
+
* const [result, error] = tryCatch(
|
|
2979
|
+
* (str: string) => JSON.parse(str),
|
|
2980
|
+
* '{"name": "Alice"}'
|
|
2981
|
+
* );
|
|
2982
|
+
*
|
|
2983
|
+
* if (error) {
|
|
2984
|
+
* console.error("Parse failed:", error);
|
|
2985
|
+
* } else {
|
|
2986
|
+
* console.log("Parsed:", result);
|
|
2987
|
+
* }
|
|
2988
|
+
* ```
|
|
2080
2989
|
*/
|
|
2081
2990
|
declare function tryCatch<T, R>(fn: (value: T) => R, value: T): [R | undefined, Error | undefined];
|
|
2082
2991
|
/**
|
|
2083
2992
|
* Async version of tryCatch
|
|
2993
|
+
*
|
|
2994
|
+
* Executes an async function and returns [result, error] tuple, providing
|
|
2995
|
+
* Go-style error handling for async operations.
|
|
2996
|
+
*
|
|
2997
|
+
* @template T - The input value type
|
|
2998
|
+
* @template R - The function's return type
|
|
2999
|
+
* @param fn - The async function to execute
|
|
3000
|
+
* @param value - The value to pass to fn
|
|
3001
|
+
* @returns A promise resolving to [result, undefined] on success or [undefined, error] on failure
|
|
3002
|
+
* @example
|
|
3003
|
+
* ```typescript
|
|
3004
|
+
* const [data, error] = await tryCatchAsync(
|
|
3005
|
+
* async (url: string) => {
|
|
3006
|
+
* const response = await fetch(url);
|
|
3007
|
+
* return response.json();
|
|
3008
|
+
* },
|
|
3009
|
+
* '/api/users'
|
|
3010
|
+
* );
|
|
3011
|
+
*
|
|
3012
|
+
* if (error) {
|
|
3013
|
+
* console.error("Request failed:", error);
|
|
3014
|
+
* } else {
|
|
3015
|
+
* console.log("Data:", data);
|
|
3016
|
+
* }
|
|
3017
|
+
* ```
|
|
2084
3018
|
*/
|
|
2085
3019
|
declare function tryCatchAsync<T, R>(fn: (value: T) => Promise<R>, value: T): Promise<[R | undefined, Error | undefined]>;
|
|
2086
3020
|
/**
|
|
@@ -2095,22 +3029,131 @@ type Result<T, E = Error> = {
|
|
|
2095
3029
|
};
|
|
2096
3030
|
/**
|
|
2097
3031
|
* Wraps a function to return a Result type
|
|
3032
|
+
*
|
|
3033
|
+
* Transforms a throwing function into one that returns a discriminated union
|
|
3034
|
+
* Result type ({ success: true, value } | { success: false, error }).
|
|
3035
|
+
* Enables type-safe error handling with exhaustive checking.
|
|
3036
|
+
*
|
|
3037
|
+
* @template T - The input value type
|
|
3038
|
+
* @template R - The function's return type
|
|
3039
|
+
* @param fn - The function that may throw
|
|
3040
|
+
* @returns A wrapped function that returns a Result type
|
|
3041
|
+
* @example
|
|
3042
|
+
* ```typescript
|
|
3043
|
+
* const parseJson = toResult((str: string) => JSON.parse(str));
|
|
3044
|
+
*
|
|
3045
|
+
* const result = parseJson('{"name": "Alice"}');
|
|
3046
|
+
* if (result.success) {
|
|
3047
|
+
* console.log(result.value.name); // Type-safe access
|
|
3048
|
+
* } else {
|
|
3049
|
+
* console.error(result.error.message); // Type-safe error handling
|
|
3050
|
+
* }
|
|
3051
|
+
* ```
|
|
2098
3052
|
*/
|
|
2099
3053
|
declare function toResult<T, R>(fn: (value: T) => R): (value: T) => Result<R>;
|
|
2100
3054
|
/**
|
|
2101
3055
|
* Async version of toResult
|
|
3056
|
+
*
|
|
3057
|
+
* Wraps an async function to return a Result type instead of throwing.
|
|
3058
|
+
* Provides type-safe error handling for async operations.
|
|
3059
|
+
*
|
|
3060
|
+
* @template T - The input value type
|
|
3061
|
+
* @template R - The function's return type
|
|
3062
|
+
* @param fn - The async function that may throw
|
|
3063
|
+
* @returns A wrapped async function that returns a Result type
|
|
3064
|
+
* @example
|
|
3065
|
+
* ```typescript
|
|
3066
|
+
* const fetchUser = toResultAsync(async (id: string) => {
|
|
3067
|
+
* const response = await fetch(`/api/users/${id}`);
|
|
3068
|
+
* return response.json();
|
|
3069
|
+
* });
|
|
3070
|
+
*
|
|
3071
|
+
* const result = await fetchUser('123');
|
|
3072
|
+
* if (result.success) {
|
|
3073
|
+
* console.log(result.value.name);
|
|
3074
|
+
* } else {
|
|
3075
|
+
* console.error("Fetch failed:", result.error);
|
|
3076
|
+
* }
|
|
3077
|
+
* ```
|
|
2102
3078
|
*/
|
|
2103
3079
|
declare function toResultAsync<T, R>(fn: (value: T) => Promise<R>): (value: T) => Promise<Result<R>>;
|
|
2104
3080
|
/**
|
|
2105
3081
|
* Guards a predicate function to return false on error instead of throwing
|
|
3082
|
+
*
|
|
3083
|
+
* Wraps a predicate to prevent errors from breaking filter/find operations.
|
|
3084
|
+
* Returns the default value (false by default) when the predicate throws.
|
|
3085
|
+
*
|
|
3086
|
+
* @template T - The value type being tested
|
|
3087
|
+
* @param predicate - The predicate function that may throw
|
|
3088
|
+
* @param defaultValue - The value to return on error (default: false)
|
|
3089
|
+
* @returns A safe predicate that never throws
|
|
3090
|
+
* @example
|
|
3091
|
+
* ```typescript
|
|
3092
|
+
* const hasValidId = safePredicate(
|
|
3093
|
+
* (user: any) => user.id > 0,
|
|
3094
|
+
* false
|
|
3095
|
+
* );
|
|
3096
|
+
*
|
|
3097
|
+
* [{ id: 1 }, { id: null }, { id: 3 }].filter(hasValidId);
|
|
3098
|
+
* // Returns [{ id: 1 }, { id: 3 }] - null.id doesn't throw
|
|
3099
|
+
* ```
|
|
2106
3100
|
*/
|
|
2107
3101
|
declare function safePredicate<T>(predicate: (value: T, index?: number) => boolean, defaultValue?: boolean): (value: T, index?: number) => boolean;
|
|
2108
3102
|
/**
|
|
2109
3103
|
* Guards a comparator function to handle errors gracefully
|
|
3104
|
+
*
|
|
3105
|
+
* Wraps a comparator to prevent errors from breaking sort operations.
|
|
3106
|
+
* Returns the default comparison value (0 by default) when the comparator throws.
|
|
3107
|
+
*
|
|
3108
|
+
* @template T - The value type being compared
|
|
3109
|
+
* @param comparator - The comparator function that may throw
|
|
3110
|
+
* @param defaultComparison - The value to return on error (default: 0, meaning equal)
|
|
3111
|
+
* @returns A safe comparator that never throws
|
|
3112
|
+
* @example
|
|
3113
|
+
* ```typescript
|
|
3114
|
+
* const byAge = safeComparator(
|
|
3115
|
+
* (a: any, b: any) => a.age - b.age,
|
|
3116
|
+
* 0
|
|
3117
|
+
* );
|
|
3118
|
+
*
|
|
3119
|
+
* [{ age: 30 }, { age: null }, { age: 25 }].sort(byAge);
|
|
3120
|
+
* // Doesn't throw when comparing with null
|
|
3121
|
+
* ```
|
|
2110
3122
|
*/
|
|
2111
3123
|
declare function safeComparator<T>(comparator: (a: T, b: T) => number, defaultComparison?: number): (a: T, b: T) => number;
|
|
2112
3124
|
/**
|
|
2113
3125
|
* Creates an error boundary that catches and logs errors
|
|
3126
|
+
*
|
|
3127
|
+
* Wraps a function with configurable error handling, allowing custom error logging,
|
|
3128
|
+
* optional re-throwing, and default value fallbacks. Ideal for top-level error
|
|
3129
|
+
* boundaries or instrumentation.
|
|
3130
|
+
*
|
|
3131
|
+
* @template T - The function's argument types as a tuple
|
|
3132
|
+
* @template R - The function's return type
|
|
3133
|
+
* @param fn - The function to wrap with error boundary
|
|
3134
|
+
* @param options - Error handling configuration
|
|
3135
|
+
* @param options.onError - Callback invoked when an error occurs, before rethrowing or returning default
|
|
3136
|
+
* @param options.rethrow - Whether to rethrow the error after logging (default: true)
|
|
3137
|
+
* @param options.defaultValue - Value to return instead of rethrowing (only used if rethrow is false)
|
|
3138
|
+
* @returns A wrapped function with error boundary
|
|
3139
|
+
* @throws The original error if rethrow is true (default behavior)
|
|
3140
|
+
* @example
|
|
3141
|
+
* ```typescript
|
|
3142
|
+
* const processWithLogging = errorBoundary(
|
|
3143
|
+
* (data: unknown) => JSON.parse(data as string),
|
|
3144
|
+
* {
|
|
3145
|
+
* onError: (error, [data]) => {
|
|
3146
|
+
* console.error("Parse failed for:", data, error);
|
|
3147
|
+
* sendToErrorTracking(error);
|
|
3148
|
+
* },
|
|
3149
|
+
* rethrow: false,
|
|
3150
|
+
* defaultValue: {}
|
|
3151
|
+
* }
|
|
3152
|
+
* );
|
|
3153
|
+
*
|
|
3154
|
+
* const result = processWithLogging('invalid json');
|
|
3155
|
+
* // Logs error but returns {} instead of throwing
|
|
3156
|
+
* ```
|
|
2114
3157
|
*/
|
|
2115
3158
|
declare function errorBoundary<T extends any[], R>(fn: (...args: T) => R, options?: {
|
|
2116
3159
|
onError?: (error: Error, args: T) => void;
|
|
@@ -2243,8 +3286,6 @@ declare namespace iter {
|
|
|
2243
3286
|
* Uses a custom comparator if provided, otherwise uses default < comparison.
|
|
2244
3287
|
*
|
|
2245
3288
|
* @template T The type of elements in all iterables
|
|
2246
|
-
* @param iterables - Variable number of sorted iterables to merge
|
|
2247
|
-
* @param compareFn - Optional comparison function (returns negative if a < b, positive if a > b, 0 if equal)
|
|
2248
3289
|
* @returns A new iterflow with all elements merged in sorted order
|
|
2249
3290
|
* @example
|
|
2250
3291
|
* ```typescript
|