-
-
Notifications
You must be signed in to change notification settings - Fork 502
/
Array.ts
3020 lines (2839 loc) · 87.7 KB
/
Array.ts
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
/**
* The Array module provides tools for working with Typescript's Array<T> type in a functional way.
*
* In functional jargon, this module provides a monadic interface over Typescript's Array<T>.
*
* @since 2.0.0
*/
import { Alt1 } from './Alt'
import { Alternative1 } from './Alternative'
import { Applicative as ApplicativeHKT, Applicative1 } from './Applicative'
import { apFirst as apFirst_, Apply1, apS as apS_, apSecond as apSecond_ } from './Apply'
import { bind as bind_, Chain1, chainFirst as chainFirst_ } from './Chain'
import { ChainRec1 } from './ChainRec'
import { Compactable1 } from './Compactable'
import { Either } from './Either'
import { Eq } from './Eq'
import { Extend1 } from './Extend'
import { Filterable1 } from './Filterable'
import { FilterableWithIndex1, PredicateWithIndex, RefinementWithIndex } from './FilterableWithIndex'
import { Foldable1 } from './Foldable'
import { FoldableWithIndex1 } from './FoldableWithIndex'
import { FromEither1, fromEitherK as fromEitherK_ } from './FromEither'
import { dual, identity, LazyArg, pipe } from './function'
import { bindTo as bindTo_, flap as flap_, Functor1, let as let__ } from './Functor'
import { FunctorWithIndex1 } from './FunctorWithIndex'
import { HKT } from './HKT'
import * as _ from './internal'
import { Magma } from './Magma'
import { Monad1 } from './Monad'
import { Monoid } from './Monoid'
import * as NEA from './NonEmptyArray'
import { Option } from './Option'
import { Ord } from './Ord'
import { Pointed1 } from './Pointed'
import { Predicate } from './Predicate'
import * as RA from './ReadonlyArray'
import { Refinement } from './Refinement'
import { Semigroup } from './Semigroup'
import { Separated, separated } from './Separated'
import { Show } from './Show'
import { PipeableTraverse1, Traversable1 } from './Traversable'
import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex'
import { Unfoldable1 } from './Unfoldable'
import {
filterE as filterE_,
PipeableWilt1,
PipeableWither1,
wiltDefault,
Witherable1,
witherDefault
} from './Witherable'
import { guard as guard_, Zero1 } from './Zero'
import NonEmptyArray = NEA.NonEmptyArray
// -------------------------------------------------------------------------------------
// refinements
// -------------------------------------------------------------------------------------
/**
* Test whether an array is empty
*
* @example
* import { isEmpty } from 'fp-ts/Array'
*
* assert.strictEqual(isEmpty([]), true)
* assert.strictEqual(isEmpty(['a']), false)
*
* @category refinements
* @since 2.0.0
*/
export const isEmpty = <A>(as: Array<A>): as is [] => as.length === 0
/**
* Test whether an array is non empty narrowing down the type to `NonEmptyArray<A>`
*
* @example
* import { isNonEmpty } from 'fp-ts/Array'
*
* assert.strictEqual(isNonEmpty([]), false)
* assert.strictEqual(isNonEmpty(['a']), true)
*
* @category refinements
* @since 2.0.0
*/
export const isNonEmpty: <A>(as: Array<A>) => as is NonEmptyArray<A> = NEA.isNonEmpty
// -------------------------------------------------------------------------------------
// constructors
// -------------------------------------------------------------------------------------
/**
* Prepend an element to the front of a `Array`, creating a new `NonEmptyArray`.
*
* @example
* import { prepend } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe([2, 3, 4], prepend(1)), [1, 2, 3, 4])
*
* @since 2.10.0
*/
export const prepend: <A>(head: A) => (tail: Array<A>) => NEA.NonEmptyArray<A> = NEA.prepend
/**
* Less strict version of [`prepend`](#prepend).
*
* @example
* import { prependW } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe([2, 3, 4], prependW("a")), ["a", 2, 3, 4]);
*
* @since 2.11.0
*/
export const prependW: <A, B>(head: B) => (tail: Array<A>) => NEA.NonEmptyArray<A | B> = NEA.prependW
/**
* Append an element to the end of a `Array`, creating a new `NonEmptyArray`.
*
* @example
* import { append } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe([1, 2, 3], append(4)), [1, 2, 3, 4])
*
* @since 2.10.0
*/
export const append: <A>(end: A) => (init: Array<A>) => NEA.NonEmptyArray<A> = NEA.append
/**
* Less strict version of [`append`](#append).
*
* @example
* import { appendW } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe([1, 2, 3], appendW("d")), [1, 2, 3, "d"]);
*
* @since 2.11.0
*/
export const appendW: <A, B>(end: B) => (init: Array<A>) => NEA.NonEmptyArray<A | B> = NEA.appendW
/**
* Return a `Array` of length `n` with element `i` initialized with `f(i)`.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { makeBy } from 'fp-ts/Array'
*
* const double = (i: number): number => i * 2
* assert.deepStrictEqual(makeBy(5, double), [0, 2, 4, 6, 8])
* assert.deepStrictEqual(makeBy(-3, double), [])
* assert.deepStrictEqual(makeBy(4.32164, double), [0, 2, 4, 6])
*
* @category constructors
* @since 2.0.0
*/
export const makeBy = <A>(n: number, f: (i: number) => A): Array<A> => (n <= 0 ? [] : NEA.makeBy(f)(n))
/**
* Create a `Array` containing a value repeated the specified number of times.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { replicate } from 'fp-ts/Array'
*
* assert.deepStrictEqual(replicate(3, 'a'), ['a', 'a', 'a'])
* assert.deepStrictEqual(replicate(-3, 'a'), [])
* assert.deepStrictEqual(replicate(2.985647, 'a'), ['a', 'a'])
*
* @category constructors
* @since 2.0.0
*/
export const replicate = <A>(n: number, a: A): Array<A> => makeBy(n, () => a)
/**
* Create an array with one element, if the element satisfies the predicate, otherwise
* it returns an empty array.
*
* @example
* import { fromPredicate } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
* import { isString } from "fp-ts/string";
*
* assert.deepStrictEqual(pipe("a", fromPredicate(isString)), ["a"]);
* assert.deepStrictEqual(pipe(7, fromPredicate(isString)), []);
*
* assert.deepStrictEqual(pipe(7, fromPredicate((x)=> x > 0)), [7]);
* assert.deepStrictEqual(pipe(-3, fromPredicate((x)=> x > 0)), []);
*
* @category lifting
* @since 2.11.0
*/
export function fromPredicate<A, B extends A>(refinement: Refinement<A, B>): (a: A) => Array<B>
export function fromPredicate<A>(predicate: Predicate<A>): <B extends A>(b: B) => Array<B>
export function fromPredicate<A>(predicate: Predicate<A>): (a: A) => Array<A>
export function fromPredicate<A>(predicate: Predicate<A>): (a: A) => Array<A> {
return (a) => (predicate(a) ? [a] : [])
}
// -------------------------------------------------------------------------------------
// conversions
// -------------------------------------------------------------------------------------
/**
* Create an array from an `Option`. The resulting array will contain the content of the
* `Option` if it is `Some` and it will be empty if the `Option` is `None`.
*
* @example
* import { fromOption } from 'fp-ts/Array'
* import { option } from "fp-ts";
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe(option.some("a"), fromOption),["a"])
* assert.deepStrictEqual(pipe(option.none, fromOption),[])
*
* @category conversions
* @since 2.11.0
*/
export const fromOption: <A>(fa: Option<A>) => Array<A> = (ma) => (_.isNone(ma) ? [] : [ma.value])
/**
* Create an array from an `Either`. The resulting array will contain the content of the
* `Either` if it is `Right` and it will be empty if the `Either` is `Left`.
*
* @example
* import { fromEither } from 'fp-ts/Array'
* import { either } from "fp-ts";
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe(either.right("r"), fromEither), ["r"]);
* assert.deepStrictEqual(pipe(either.left("l"), fromEither), []);
*
* @category conversions
* @since 2.11.0
*/
export const fromEither: <A>(fa: Either<unknown, A>) => Array<A> = (e) => (_.isLeft(e) ? [] : [e.right])
/**
* Less strict version of [`match`](#match).
*
* The `W` suffix (short for **W**idening) means that the handler return types will be merged.
*
* @example
* import { matchW } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* const matcherW = matchW(
* () => "No elements",
* (as) => as.length
* );
* assert.deepStrictEqual(pipe([1, 2, 3, 4], matcherW), 4);
* assert.deepStrictEqual(pipe([], matcherW), "No elements");
*
* @category pattern matching
* @since 2.11.0
*/
export const matchW =
<B, A, C>(onEmpty: LazyArg<B>, onNonEmpty: (as: NonEmptyArray<A>) => C) =>
(as: Array<A>): B | C =>
isNonEmpty(as) ? onNonEmpty(as) : onEmpty()
/**
* Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise
* it passes the array to `onNonEmpty` and returns the result.
*
* @example
* import { match } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* const matcher = match(
* () => "No elements",
* (as) => `Found ${as.length} element(s)`
* );
* assert.deepStrictEqual(pipe([1, 2, 3, 4], matcher), "Found 4 element(s)");
* assert.deepStrictEqual(pipe([], matcher), "No elements");
*
* @category pattern matching
* @since 2.11.0
*/
export const match: <B, A>(onEmpty: LazyArg<B>, onNonEmpty: (as: NonEmptyArray<A>) => B) => (as: Array<A>) => B = matchW
/**
* Less strict version of [`matchLeft`](#matchleft). It will work when `onEmpty` and
* `onNonEmpty` have different return types.
*
* @example
* import { matchLeftW } from 'fp-ts/Array'
*
* const f = matchLeftW(
* () => 0,
* (head: string, tail: string[]) => `Found "${head}" followed by ${tail.length} elements`
* );
* assert.strictEqual(f(["a", "b", "c"]), 'Found "a" followed by 2 elements');
* assert.strictEqual(f([]), 0);
*
* @category pattern matching
* @since 2.11.0
*/
export const matchLeftW =
<B, A, C>(onEmpty: LazyArg<B>, onNonEmpty: (head: A, tail: Array<A>) => C) =>
(as: Array<A>): B | C =>
isNonEmpty(as) ? onNonEmpty(NEA.head(as), NEA.tail(as)) : onEmpty()
/**
* Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise
* it passes the array to `onNonEmpty` broken into its first element and remaining elements.
*
* @example
* import { matchLeft } from 'fp-ts/Array'
*
* const len: <A>(as: Array<A>) => number = matchLeft(() => 0, (_, tail) => 1 + len(tail))
* assert.strictEqual(len([1, 2, 3]), 3)
*
* @category pattern matching
* @since 2.10.0
*/
export const matchLeft: <B, A>(onEmpty: LazyArg<B>, onNonEmpty: (head: A, tail: Array<A>) => B) => (as: Array<A>) => B =
matchLeftW
/**
* Alias of [`matchLeft`](#matchleft).
*
* @category pattern matching
* @since 2.0.0
*/
export const foldLeft: <A, B>(onEmpty: LazyArg<B>, onNonEmpty: (head: A, tail: Array<A>) => B) => (as: Array<A>) => B =
matchLeft
/**
* Less strict version of [`matchRight`](#matchright). It will work when `onEmpty` and
* `onNonEmpty` have different return types.
*
* @example
* import { matchRightW } from 'fp-ts/Array'
*
* const f = matchRightW(
* () => 0,
* (head: string[], tail: string) => `Found ${head.length} elements folllowed by "${tail}"`
* );
* assert.strictEqual(f(["a", "b", "c"]), 'Found 2 elements folllowed by "c"');
* assert.strictEqual(f([]), 0);
*
* @category pattern matching
* @since 2.11.0
*/
export const matchRightW =
<B, A, C>(onEmpty: LazyArg<B>, onNonEmpty: (init: Array<A>, last: A) => C) =>
(as: Array<A>): B | C =>
isNonEmpty(as) ? onNonEmpty(NEA.init(as), NEA.last(as)) : onEmpty()
/**
* Takes an array, if the array is empty it returns the result of `onEmpty`, otherwise
* it passes the array to `onNonEmpty` broken into its initial elements and the last element.
*
* @example
* import { matchRight } from 'fp-ts/Array'
*
* const len: <A>(as: Array<A>) => number = matchRight(
* () => 0,
* (head, _) => 1 + len(head)
* );
* assert.strictEqual(len([1, 2, 3]), 3);
*
* @category pattern matching
* @since 2.10.0
*/
export const matchRight: <B, A>(
onEmpty: LazyArg<B>,
onNonEmpty: (init: Array<A>, last: A) => B
) => (as: Array<A>) => B = matchRightW
/**
* Alias of [`matchRight`](#matchright).
*
* @category pattern matching
* @since 2.0.0
*/
export const foldRight: <A, B>(onEmpty: LazyArg<B>, onNonEmpty: (init: Array<A>, last: A) => B) => (as: Array<A>) => B =
matchRight
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
/**
* Same as [`chain`](#chain), but passing also the index to the iterating function.
*
* @example
* import { chainWithIndex, replicate } from 'fp-ts/Array'
* import { pipe } from 'fp-ts/function'
*
* const f = (index: number, x: string) => replicate(2, `${x}${index}`);
* assert.deepStrictEqual(pipe(["a", "b", "c"], chainWithIndex(f)), ["a0", "a0", "b1", "b1", "c2", "c2"]);
*
* @category sequencing
* @since 2.7.0
*/
export const chainWithIndex =
<A, B>(f: (i: number, a: A) => Array<B>) =>
(as: Array<A>): Array<B> => {
const out: Array<B> = []
for (let i = 0; i < as.length; i++) {
const bs = f(i, as[i])
for (let j = 0; j < bs.length; j++) {
out.push(bs[j])
}
}
return out
}
/**
* Same as `reduce` but it carries over the intermediate steps
*
* @example
* import { scanLeft } from 'fp-ts/Array'
*
* assert.deepStrictEqual(scanLeft(10, (b, a: number) => b - a)([1, 2, 3]), [10, 9, 7, 4])
*
* @since 2.0.0
*/
export const scanLeft =
<A, B>(b: B, f: (b: B, a: A) => B) =>
(as: Array<A>): NonEmptyArray<B> => {
const len = as.length
const out = new Array(len + 1) as NonEmptyArray<B>
out[0] = b
for (let i = 0; i < len; i++) {
out[i + 1] = f(out[i], as[i])
}
return out
}
/**
* Fold an array from the right, keeping all intermediate results instead of only the final result
*
* @example
* import { scanRight } from 'fp-ts/Array'
*
* assert.deepStrictEqual(scanRight(10, (a: number, b) => b - a)([1, 2, 3]), [4, 5, 7, 10])
*
* @since 2.0.0
*/
export const scanRight =
<A, B>(b: B, f: (a: A, b: B) => B) =>
(as: Array<A>): NonEmptyArray<B> => {
const len = as.length
const out = new Array(len + 1) as NonEmptyArray<B>
out[len] = b
for (let i = len - 1; i >= 0; i--) {
out[i] = f(as[i], out[i + 1])
}
return out
}
/**
* Calculate the number of elements in a `Array`.
*
* @example
* import { size } from 'fp-ts/Array'
*
* assert.strictEqual(size(["a","b","c"]),3)
*
* @since 2.10.0
*/
export const size = <A>(as: Array<A>): number => as.length
/**
* Test whether an array contains a particular index
*
* @example
* import { isOutOfBound } from 'fp-ts/Array'
*
* assert.strictEqual(isOutOfBound(1,["a","b","c"]),false)
* assert.strictEqual(isOutOfBound(-1,["a","b","c"]),true)
* assert.strictEqual(isOutOfBound(3,["a","b","c"]),true)
*
* @since 2.0.0
*/
export const isOutOfBound: <A>(i: number, as: Array<A>) => boolean = NEA.isOutOfBound
// TODO: remove non-curried overloading in v3
/**
* This function provides a safe way to read a value at a particular index from an array.
* It returns a `none` if the index is out of bounds, and a `some` of the element if the
* index is valid.
*
* @example
* import { lookup } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe([1, 2, 3], lookup(1)), some(2))
* assert.deepStrictEqual(pipe([1, 2, 3], lookup(3)), none)
*
* @since 2.0.0
*/
export const lookup: {
(i: number): <A>(as: Array<A>) => Option<A>
<A>(i: number, as: Array<A>): Option<A>
} = RA.lookup
/**
* Get the first element in an array, or `None` if the array is empty
*
* @example
* import { head } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(head([1, 2, 3]), some(1))
* assert.deepStrictEqual(head([]), none)
*
* @since 2.0.0
*/
export const head: <A>(as: Array<A>) => Option<A> = RA.head
/**
* Get the last element in an array, or `None` if the array is empty
*
* @example
* import { last } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(last([1, 2, 3]), some(3))
* assert.deepStrictEqual(last([]), none)
*
* @since 2.0.0
*/
export const last: <A>(as: Array<A>) => Option<A> = RA.last
/**
* Get all but the first element of an array, creating a new array, or `None` if the array is empty
*
* @example
* import { tail } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(tail([1, 2, 3]), some([2, 3]))
* assert.deepStrictEqual(tail([]), none)
*
* @since 2.0.0
*/
export const tail = <A>(as: Array<A>): Option<Array<A>> => (isNonEmpty(as) ? _.some(NEA.tail(as)) : _.none)
/**
* Get all but the last element of an array, creating a new array, or `None` if the array is empty
*
* @example
* import { init } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(init([1, 2, 3]), some([1, 2]))
* assert.deepStrictEqual(init([]), none)
*
* @since 2.0.0
*/
export const init = <A>(as: Array<A>): Option<Array<A>> => (isNonEmpty(as) ? _.some(NEA.init(as)) : _.none)
/**
* Keep only a max number of elements from the start of an `Array`, creating a new `Array`.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { takeLeft } from 'fp-ts/Array'
*
* assert.deepStrictEqual(takeLeft(2)([1, 2, 3, 4, 5]), [1, 2]);
* assert.deepStrictEqual(takeLeft(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]);
* assert.deepStrictEqual(takeLeft(0)([1, 2, 3, 4, 5]), []);
* assert.deepStrictEqual(takeLeft(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]);
*
* @since 2.0.0
*/
export const takeLeft =
(n: number) =>
<A>(as: Array<A>): Array<A> =>
isOutOfBound(n, as) ? copy(as) : as.slice(0, n)
/**
* Keep only a max number of elements from the end of an `Array`, creating a new `Array`.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { takeRight } from 'fp-ts/Array'
*
* assert.deepStrictEqual(takeRight(2)([1, 2, 3, 4, 5]), [4, 5]);
* assert.deepStrictEqual(takeRight(7)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]);
* assert.deepStrictEqual(takeRight(0)([1, 2, 3, 4, 5]), []);
* assert.deepStrictEqual(takeRight(-1)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5]);
*
* @since 2.0.0
*/
export const takeRight =
(n: number) =>
<A>(as: Array<A>): Array<A> =>
isOutOfBound(n, as) ? copy(as) : n === 0 ? [] : as.slice(-n)
/**
* Calculate the longest initial subarray for which all element satisfy the specified predicate, creating a new array
*
* @example
* import { takeLeftWhile } from 'fp-ts/Array'
*
* assert.deepStrictEqual(takeLeftWhile((n: number) => n % 2 === 0)([2, 4, 3, 6]), [2, 4])
*
* @since 2.0.0
*/
export function takeLeftWhile<A, B extends A>(refinement: Refinement<A, B>): (as: Array<A>) => Array<B>
export function takeLeftWhile<A>(predicate: Predicate<A>): <B extends A>(bs: Array<B>) => Array<B>
export function takeLeftWhile<A>(predicate: Predicate<A>): (as: Array<A>) => Array<A>
export function takeLeftWhile<A>(predicate: Predicate<A>): (as: Array<A>) => Array<A> {
return (as: Array<A>) => {
const out: Array<A> = []
for (const a of as) {
if (!predicate(a)) {
break
}
out.push(a)
}
return out
}
}
const spanLeftIndex = <A>(as: Array<A>, predicate: Predicate<A>): number => {
const l = as.length
let i = 0
for (; i < l; i++) {
if (!predicate(as[i])) {
break
}
}
return i
}
/**
* Type returned by [`spanLeft`](#spanLeft) composed of an `init` array and a `rest` array.
*
* @since 2.10.0
*/
export interface Spanned<I, R> {
init: Array<I>
rest: Array<R>
}
/**
* Split an array into two parts:
* 1. the longest initial subarray for which all elements satisfy the specified predicate
* 2. the remaining elements
*
* @example
* import { spanLeft } from 'fp-ts/Array'
*
* const isOdd = (n: number) => n % 2 === 1;
* assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] });
* assert.deepStrictEqual(spanLeft(isOdd)([0, 2, 4, 5]), { init: [], rest: [0, 2, 4, 5] });
* assert.deepStrictEqual(spanLeft(isOdd)([1, 3, 5]), { init: [1, 3, 5], rest: [] });
*
* @since 2.0.0
*/
export function spanLeft<A, B extends A>(refinement: Refinement<A, B>): (as: Array<A>) => Spanned<B, A>
export function spanLeft<A>(predicate: Predicate<A>): <B extends A>(bs: Array<B>) => Spanned<B, B>
export function spanLeft<A>(predicate: Predicate<A>): (as: Array<A>) => Spanned<A, A>
export function spanLeft<A>(predicate: Predicate<A>): (as: Array<A>) => Spanned<A, A> {
return (as) => {
const [init, rest] = splitAt(spanLeftIndex(as, predicate))(as)
return { init, rest }
}
}
/**
* Creates a new `Array` which is a copy of the input dropping a max number of elements from the start.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { dropLeft } from 'fp-ts/Array'
*
* assert.deepStrictEqual(dropLeft(2)([1, 2, 3]), [3]);
* assert.deepStrictEqual(dropLeft(5)([1, 2, 3]), []);
* assert.deepStrictEqual(dropLeft(0)([1, 2, 3]), [1, 2, 3]);
* assert.deepStrictEqual(dropLeft(-2)([1, 2, 3]), [1, 2, 3]);
*
* @since 2.0.0
*/
export const dropLeft =
(n: number) =>
<A>(as: Array<A>): Array<A> =>
n <= 0 || isEmpty(as) ? copy(as) : n >= as.length ? [] : as.slice(n, as.length)
/**
* Creates a new `Array` which is a copy of the input dropping a max number of elements from the end.
*
* **Note**. `n` is normalized to a non negative integer.
*
* @example
* import { dropRight } from 'fp-ts/Array'
*
* assert.deepStrictEqual(dropRight(2)([1, 2, 3]), [1]);
* assert.deepStrictEqual(dropRight(5)([1, 2, 3]), []);
* assert.deepStrictEqual(dropRight(0)([1, 2, 3]), [1, 2, 3]);
* assert.deepStrictEqual(dropRight(-2)([1, 2, 3]), [1, 2, 3]);
*
* @since 2.0.0
*/
export const dropRight =
(n: number) =>
<A>(as: Array<A>): Array<A> =>
n <= 0 || isEmpty(as) ? copy(as) : n >= as.length ? [] : as.slice(0, as.length - n)
/**
* Creates a new `Array` which is a copy of the input dropping the longest initial subarray for
* which all element satisfy the specified predicate.
*
* @example
* import { dropLeftWhile } from 'fp-ts/Array'
*
* assert.deepStrictEqual(dropLeftWhile((n: number) => n % 2 === 1)([1, 3, 2, 4, 5]), [2, 4, 5])
*
* @since 2.0.0
*/
export function dropLeftWhile<A, B extends A>(refinement: Refinement<A, B>): (as: Array<A>) => Array<B>
export function dropLeftWhile<A>(predicate: Predicate<A>): <B extends A>(bs: Array<B>) => Array<B>
export function dropLeftWhile<A>(predicate: Predicate<A>): (as: Array<A>) => Array<A>
export function dropLeftWhile<A>(predicate: Predicate<A>): (as: Array<A>) => Array<A> {
return (as) => as.slice(spanLeftIndex(as, predicate))
}
/**
* `findIndex` returns an `Option` containing the first index for which a predicate holds.
* It returns `None` if no element satisfies the predicate.
* Similar to [`findFirst`](#findFirst) but returning the index instead of the element.
*
* @example
* import { findIndex } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(findIndex((n: number) => n === 2)([1, 2, 3]), some(1))
* assert.deepStrictEqual(findIndex((n: number) => n === 2)([]), none)
*
* @since 2.0.0
*/
export const findIndex: <A>(predicate: Predicate<A>) => (as: Array<A>) => Option<number> = RA.findIndex
/**
* Find the first element which satisfies a predicate (or a refinement) function.
* It returns an `Option` containing the element or `None` if not found.
*
* @example
* import { findFirst } from 'fp-ts/Array'
* import { some } from 'fp-ts/Option'
*
* type X = {
* readonly a: number
* readonly b: number
* }
*
* assert.deepStrictEqual(findFirst((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 1 }))
*
* @since 2.0.0
*/
export function findFirst<A, B extends A>(refinement: Refinement<A, B>): (as: Array<A>) => Option<B>
export function findFirst<A>(predicate: Predicate<A>): <B extends A>(bs: Array<B>) => Option<B>
export function findFirst<A>(predicate: Predicate<A>): (as: Array<A>) => Option<A>
export function findFirst<A>(predicate: Predicate<A>): (as: Array<A>) => Option<A> {
return RA.findFirst(predicate)
}
/**
* Given a selector function which takes an element and returns an option,
* this function applies the selector to each element of the array and
* returns the first `Some` result. Otherwise it returns `None`.
*
* @example
* import { findFirstMap } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* interface Person {
* readonly name: string;
* readonly age: number;
* }
*
* const persons: Array<Person> = [
* { name: "John", age: 16 },
* { name: "Mary", age: 45 },
* { name: "Joey", age: 28 },
* ];
*
* const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name));
* const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name));
* assert.deepStrictEqual(findFirstMap(nameOfPersonAbove18)(persons), some("Mary"));
* assert.deepStrictEqual(findFirstMap(nameOfPersonAbove70)(persons), none);
*
* @since 2.0.0
*/
export const findFirstMap: <A, B>(f: (a: A) => Option<B>) => (as: Array<A>) => Option<B> = RA.findFirstMap
/**
* Find the last element which satisfies a predicate function.
* It returns an `Option` containing the element or `None` if not found.
*
* @example
* import { findLast } from 'fp-ts/Array'
* import { some } from 'fp-ts/Option'
*
* type X = {
* readonly a: number
* readonly b: number
* }
*
* assert.deepStrictEqual(findLast((x: X) => x.a === 1)([{ a: 1, b: 1 }, { a: 1, b: 2 }]), some({ a: 1, b: 2 }))
*
* @since 2.0.0
*/
export function findLast<A, B extends A>(refinement: Refinement<A, B>): (as: Array<A>) => Option<B>
export function findLast<A>(predicate: Predicate<A>): <B extends A>(bs: Array<B>) => Option<B>
export function findLast<A>(predicate: Predicate<A>): (as: Array<A>) => Option<A>
export function findLast<A>(predicate: Predicate<A>): (as: Array<A>) => Option<A> {
return RA.findLast(predicate)
}
/**
* Given a selector function which takes an element and returns an option,
* this function applies the selector to each element of the array starting from the
* end and returns the last `Some` result. Otherwise it returns `None`.
*
* @example
* import { findLastMap } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* interface Person {
* readonly name: string;
* readonly age: number;
* }
*
* const persons: Array<Person> = [
* { name: "John", age: 16 },
* { name: "Mary", age: 45 },
* { name: "Joey", age: 28 },
* ];
*
* const nameOfPersonAbove18 = (p: Person) => (p.age <= 18 ? none : some(p.name));
* const nameOfPersonAbove70 = (p: Person) => (p.age <= 70 ? none : some(p.name));
* assert.deepStrictEqual(findLastMap(nameOfPersonAbove18)(persons), some("Joey"));
* assert.deepStrictEqual(findLastMap(nameOfPersonAbove70)(persons), none);
*
* @since 2.0.0
*/
export const findLastMap: <A, B>(f: (a: A) => Option<B>) => (as: Array<A>) => Option<B> = RA.findLastMap
/**
* Returns the index of the last element of the list which matches the predicate.
* It returns an `Option` containing the index or `None` if not found.
*
* @example
* import { findLastIndex } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* interface X {
* readonly a: number
* readonly b: number
* }
* const xs: Array<X> = [{ a: 1, b: 0 }, { a: 1, b: 1 }]
* assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 1)(xs), some(1))
* assert.deepStrictEqual(findLastIndex((x: { readonly a: number }) => x.a === 4)(xs), none)
*
* @since 2.0.0
*/
export const findLastIndex: <A>(predicate: Predicate<A>) => (as: Array<A>) => Option<number> = RA.findLastIndex
/**
* This function takes an array and makes a new array containing the same elements.
*
* @since 2.0.0
*/
export const copy = <A>(as: Array<A>): Array<A> => as.slice()
/**
* Insert an element at the specified index, creating a new array,
* or returning `None` if the index is out of bounds.
*
* @example
* import { insertAt } from 'fp-ts/Array'
* import { some } from 'fp-ts/Option'
*
* assert.deepStrictEqual(insertAt(2, 5)([1, 2, 3, 4]), some([1, 2, 5, 3, 4]))
*
* @since 2.0.0
*/
export const insertAt =
<A>(i: number, a: A) =>
(as: Array<A>): Option<NonEmptyArray<A>> =>
i < 0 || i > as.length ? _.none : _.some(unsafeInsertAt(i, a, as))
/**
* Change the element at the specified index, creating a new array,
* or returning `None` if the index is out of bounds.
*
* @example
* import { updateAt } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(updateAt(1, 1)([1, 2, 3]), some([1, 1, 3]))
* assert.deepStrictEqual(updateAt(1, 1)([]), none)
*
* @since 2.0.0
*/
export const updateAt = <A>(i: number, a: A): ((as: Array<A>) => Option<Array<A>>) => modifyAt(i, () => a)
/**
* Delete the element at the specified index, creating a new array, or returning `None` if the index is out of bounds.
*
* @example
* import { deleteAt } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* assert.deepStrictEqual(deleteAt(0)([1, 2, 3]), some([2, 3]))
* assert.deepStrictEqual(deleteAt(1)([]), none)
*
* @since 2.0.0
*/
export const deleteAt =
(i: number) =>
<A>(as: Array<A>): Option<Array<A>> =>
isOutOfBound(i, as) ? _.none : _.some(unsafeDeleteAt(i, as))
/**
* Apply a function to the element at the specified index, creating a new array, or returning `None` if the index is out
* of bounds.
*
* @example
* import { modifyAt } from 'fp-ts/Array'
* import { some, none } from 'fp-ts/Option'
*
* const double = (x: number): number => x * 2
* assert.deepStrictEqual(modifyAt(1, double)([1, 2, 3]), some([1, 4, 3]))
* assert.deepStrictEqual(modifyAt(1, double)([]), none)
*
* @since 2.0.0
*/
export const modifyAt =
<A>(i: number, f: (a: A) => A) =>
(as: Array<A>): Option<Array<A>> =>
isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as))
/**
* Reverse an array, creating a new array
*
* @example
* import { reverse } from 'fp-ts/Array'
*
* assert.deepStrictEqual(reverse([1, 2, 3]), [3, 2, 1])
*
* @since 2.0.0
*/
export const reverse = <A>(as: Array<A>): Array<A> => (isEmpty(as) ? [] : as.slice().reverse())
/**
* Takes an `Array` of `Either` and produces a new `Array` containing
* the values of all the `Right` elements in the same order.
*
* @example
* import { rights } from 'fp-ts/Array'
* import { right, left } from 'fp-ts/Either'
*
* assert.deepStrictEqual(rights([right(1), left('foo'), right(2)]), [1, 2])
*
* @since 2.0.0
*/
export const rights = <E, A>(as: Array<Either<E, A>>): Array<A> => {
const r: Array<A> = []
for (let i = 0; i < as.length; i++) {
const a = as[i]
if (a._tag === 'Right') {
r.push(a.right)
}
}
return r
}
/**
* Takes an `Array` of `Either` and produces a new `Array` containing
* the values of all the `Left` elements in the same order.
*
* @example
* import { lefts } from 'fp-ts/Array'
* import { left, right } from 'fp-ts/Either'
*
* assert.deepStrictEqual(lefts([right(1), left('foo'), right(2)]), ['foo'])
*
* @since 2.0.0
*/
export const lefts = <E, A>(as: Array<Either<E, A>>): Array<E> => {
const r: Array<E> = []
for (let i = 0; i < as.length; i++) {
const a = as[i]
if (a._tag === 'Left') {