-
-
Notifications
You must be signed in to change notification settings - Fork 503
/
ReadonlyNonEmptyArray.ts
1497 lines (1373 loc) · 39 KB
/
ReadonlyNonEmptyArray.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
/**
* Data structure which represents non-empty readonly arrays.
*
* ```ts
* export type ReadonlyNonEmptyArray<A> = ReadonlyArray<A> & {
* readonly 0: A
* }
* ```
*
* Note that you don't need any conversion, a `ReadonlyNonEmptyArray` is a `ReadonlyArray`,
* so all `ReadonlyArray`'s APIs can be used with a `ReadonlyNonEmptyArray` without further ado.
*
* @since 2.5.0
*/
import { Alt1 } from './Alt'
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 { Comonad1 } from './Comonad'
import { Endomorphism } from './Endomorphism'
import { Eq, fromEquals } from './Eq'
import { Extend1 } from './Extend'
import { Foldable1 } from './Foldable'
import { FoldableWithIndex1 } from './FoldableWithIndex'
import { dual, flow, identity, LazyArg, pipe, SK } 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 { Monad1 } from './Monad'
import { NonEmptyArray } from './NonEmptyArray'
import { Option } from './Option'
import { getMonoid, Ord } from './Ord'
import { Pointed1 } from './Pointed'
import { Predicate } from './Predicate'
import { ReadonlyRecord } from './ReadonlyRecord'
import { Refinement } from './Refinement'
import * as Se from './Semigroup'
import { Show } from './Show'
import { PipeableTraverse1, Traversable1 } from './Traversable'
import { PipeableTraverseWithIndex1, TraversableWithIndex1 } from './TraversableWithIndex'
import Semigroup = Se.Semigroup
// -------------------------------------------------------------------------------------
// model
// -------------------------------------------------------------------------------------
/**
* @category model
* @since 2.5.0
*/
export type ReadonlyNonEmptyArray<A> = ReadonlyArray<A> & {
readonly 0: A
}
// -------------------------------------------------------------------------------------
// internal
// -------------------------------------------------------------------------------------
/**
* @internal
*/
export const empty: ReadonlyArray<never> = _.emptyReadonlyArray
/**
* @internal
*/
export const isNonEmpty: <A>(as: ReadonlyArray<A>) => as is ReadonlyNonEmptyArray<A> = _.isNonEmpty
/**
* @internal
*/
export const isOutOfBound = <A>(i: number, as: ReadonlyArray<A>): boolean => i < 0 || i >= as.length
/**
* @internal
*/
export const prependW =
<B>(head: B) =>
<A>(tail: ReadonlyArray<A>): ReadonlyNonEmptyArray<A | B> =>
[head, ...tail]
/**
* @internal
*/
export const prepend: <A>(head: A) => (tail: ReadonlyArray<A>) => ReadonlyNonEmptyArray<A> = prependW
/**
* @internal
*/
export const appendW =
<B>(end: B) =>
<A>(init: ReadonlyArray<A>): ReadonlyNonEmptyArray<A | B> =>
[...init, end] as any
/**
* @internal
*/
export const append: <A>(end: A) => (init: ReadonlyArray<A>) => ReadonlyNonEmptyArray<A> = appendW
/**
* @internal
*/
export const unsafeInsertAt = <A>(i: number, a: A, as: ReadonlyArray<A>): ReadonlyNonEmptyArray<A> => {
if (isNonEmpty(as)) {
const xs = _.fromReadonlyNonEmptyArray(as)
xs.splice(i, 0, a)
return xs
}
return [a]
}
/**
* @internal
*/
export const unsafeUpdateAt = <A>(i: number, a: A, as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> => {
if (as[i] === a) {
return as
} else {
const xs = _.fromReadonlyNonEmptyArray(as)
xs[i] = a
return xs
}
}
/**
* Remove duplicates from a `ReadonlyNonEmptyArray`, keeping the first occurrence of an element.
*
* @example
* import { uniq } from 'fp-ts/ReadonlyNonEmptyArray'
* import * as N from 'fp-ts/number'
*
* assert.deepStrictEqual(uniq(N.Eq)([1, 2, 1]), [1, 2])
*
* @since 2.11.0
*/
export const uniq =
<A>(E: Eq<A>) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> => {
if (as.length === 1) {
return as
}
const out: NonEmptyArray<A> = [head(as)]
const rest = tail(as)
for (const a of rest) {
if (out.every((o) => !E.equals(o, a))) {
out.push(a)
}
}
return out
}
/**
* Sort the elements of a `ReadonlyNonEmptyArray` in increasing order, where elements are compared using first `ords[0]`, then `ords[1]`,
* etc...
*
* @example
* import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray'
* import { contramap } from 'fp-ts/Ord'
* import * as S from 'fp-ts/string'
* import * as N from 'fp-ts/number'
* import { pipe } from 'fp-ts/function'
*
* interface Person {
* name: string
* age: number
* }
*
* const byName = pipe(S.Ord, contramap((p: Person) => p.name))
*
* const byAge = pipe(N.Ord, contramap((p: Person) => p.age))
*
* const sortByNameByAge = RNEA.sortBy([byName, byAge])
*
* const persons: RNEA.ReadonlyNonEmptyArray<Person> = [
* { name: 'a', age: 1 },
* { name: 'b', age: 3 },
* { name: 'c', age: 2 },
* { name: 'b', age: 2 }
* ]
*
* assert.deepStrictEqual(sortByNameByAge(persons), [
* { name: 'a', age: 1 },
* { name: 'b', age: 2 },
* { name: 'b', age: 3 },
* { name: 'c', age: 2 }
* ])
*
* @since 2.11.0
*/
export const sortBy = <B>(
ords: ReadonlyArray<Ord<B>>
): (<A extends B>(as: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<A>) => {
if (isNonEmpty(ords)) {
const M = getMonoid<B>()
return sort(ords.reduce(M.concat, M.empty))
}
return identity
}
/**
* @since 2.11.0
*/
export const union = <A>(
E: Eq<A>
): ((second: ReadonlyNonEmptyArray<A>) => (first: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<A>) => {
const uniqE = uniq(E)
return (second) => (first) => uniqE(pipe(first, concat(second)))
}
/**
* Rotate a `ReadonlyNonEmptyArray` by `n` steps.
*
* @example
* import { rotate } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
* assert.deepStrictEqual(rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
*
* @since 2.11.0
*/
export const rotate =
(n: number) =>
<A>(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> => {
const len = as.length
const m = Math.round(n) % len
if (isOutOfBound(Math.abs(m), as) || m === 0) {
return as
}
if (m < 0) {
const [f, s] = splitAt(-m)(as)
return pipe(s, concat(f))
} else {
return rotate(m - len)(as)
}
}
// -------------------------------------------------------------------------------------
// constructors
// -------------------------------------------------------------------------------------
/**
* Return a `ReadonlyNonEmptyArray` from a `ReadonlyArray` returning `none` if the input is empty.
*
* @category conversions
* @since 2.5.0
*/
export const fromReadonlyArray = <A>(as: ReadonlyArray<A>): Option<ReadonlyNonEmptyArray<A>> =>
isNonEmpty(as) ? _.some(as) : _.none
/**
* Return a `ReadonlyNonEmptyArray` of length `n` with element `i` initialized with `f(i)`.
*
* **Note**. `n` is normalized to a natural number.
*
* @example
* import { makeBy } from 'fp-ts/ReadonlyNonEmptyArray'
* import { pipe } from 'fp-ts/function'
*
* const double = (n: number): number => n * 2
* assert.deepStrictEqual(pipe(5, makeBy(double)), [0, 2, 4, 6, 8])
*
* @category constructors
* @since 2.11.0
*/
export const makeBy =
<A>(f: (i: number) => A) =>
(n: number): ReadonlyNonEmptyArray<A> => {
const j = Math.max(0, Math.floor(n))
const out: NonEmptyArray<A> = [f(0)]
for (let i = 1; i < j; i++) {
out.push(f(i))
}
return out
}
/**
* Create a `ReadonlyNonEmptyArray` containing a value repeated the specified number of times.
*
* **Note**. `n` is normalized to a natural number.
*
* @example
* import { replicate } from 'fp-ts/ReadonlyNonEmptyArray'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(pipe(3, replicate('a')), ['a', 'a', 'a'])
*
* @category constructors
* @since 2.11.0
*/
export const replicate = <A>(a: A): ((n: number) => ReadonlyNonEmptyArray<A>) => makeBy(() => a)
/**
* Create a `ReadonlyNonEmptyArray` containing a range of integers, including both endpoints.
*
* @example
* import { range } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(range(1, 5), [1, 2, 3, 4, 5])
*
* @category constructors
* @since 2.11.0
*/
export const range = (start: number, end: number): ReadonlyNonEmptyArray<number> =>
start <= end ? makeBy((i) => start + i)(end - start + 1) : [start]
/**
* Return the tuple of the `head` and the `tail`.
*
* @example
* import { unprepend } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(unprepend([1, 2, 3, 4]), [1, [2, 3, 4]])
*
* @since 2.9.0
*/
export const unprepend = <A>(as: ReadonlyNonEmptyArray<A>): readonly [A, ReadonlyArray<A>] => [head(as), tail(as)]
/**
* Return the tuple of the `init` and the `last`.
*
* @example
* import { unappend } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(unappend([1, 2, 3, 4]), [[1, 2, 3], 4])
*
* @since 2.9.0
*/
export const unappend = <A>(as: ReadonlyNonEmptyArray<A>): readonly [ReadonlyArray<A>, A] => [init(as), last(as)]
/**
* @category conversions
* @since 2.5.0
*/
export const fromArray = <A>(as: Array<A>): Option<ReadonlyNonEmptyArray<A>> => fromReadonlyArray(as.slice())
// -------------------------------------------------------------------------------------
// combinators
// -------------------------------------------------------------------------------------
/**
* @since 2.11.0
*/
export function concatW<B>(
second: ReadonlyNonEmptyArray<B>
): <A>(first: ReadonlyArray<A>) => ReadonlyNonEmptyArray<A | B>
export function concatW<B>(
second: ReadonlyArray<B>
): <A>(first: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<A | B>
export function concatW<B>(second: ReadonlyArray<B>): <A>(first: ReadonlyNonEmptyArray<A>) => ReadonlyArray<A | B> {
return <A>(first: ReadonlyNonEmptyArray<A | B>) => first.concat(second)
}
/**
* @since 2.5.0
*/
export function concat<A>(second: ReadonlyNonEmptyArray<A>): (first: ReadonlyArray<A>) => ReadonlyNonEmptyArray<A>
export function concat<A>(second: ReadonlyArray<A>): (first: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<A>
/** @deprecated */
export function concat<A>(first: ReadonlyArray<A>, second: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A>
/** @deprecated */
export function concat<A>(first: ReadonlyNonEmptyArray<A>, second: ReadonlyArray<A>): ReadonlyNonEmptyArray<A>
export function concat<A>(
x: ReadonlyArray<A>,
y?: ReadonlyArray<A>
): ReadonlyArray<A> | ((y: ReadonlyNonEmptyArray<A>) => ReadonlyArray<A>) {
return y ? x.concat(y) : (y) => y.concat(x)
}
/**
* @since 2.5.0
*/
export const reverse = <A>(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> =>
as.length === 1 ? as : [last(as), ...as.slice(0, -1).reverse()]
/**
* Group equal, consecutive elements of a `ReadonlyArray` into `ReadonlyNonEmptyArray`s.
*
* @example
* import { group } from 'fp-ts/ReadonlyNonEmptyArray'
* import * as N from 'fp-ts/number'
*
* assert.deepStrictEqual(group(N.Eq)([1, 2, 1, 1]), [
* [1],
* [2],
* [1, 1]
* ])
*
* @since 2.5.0
*/
export function group<B>(E: Eq<B>): {
<A extends B>(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<ReadonlyNonEmptyArray<A>>
<A extends B>(as: ReadonlyArray<A>): ReadonlyArray<ReadonlyNonEmptyArray<A>>
}
export function group<A>(E: Eq<A>): (as: ReadonlyArray<A>) => ReadonlyArray<ReadonlyNonEmptyArray<A>> {
return (as) => {
const len = as.length
if (len === 0) {
return empty
}
const out: Array<ReadonlyNonEmptyArray<A>> = []
let head: A = as[0]
let nea: NonEmptyArray<A> = [head]
for (let i = 1; i < len; i++) {
const a = as[i]
if (E.equals(a, head)) {
nea.push(a)
} else {
out.push(nea)
head = a
nea = [head]
}
}
out.push(nea)
return out
}
}
/**
* Splits an array into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning
* function on each element, and grouping the results according to values returned
*
* @example
* import { groupBy } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(groupBy((s: string) => String(s.length))(['a', 'b', 'ab']), {
* '1': ['a', 'b'],
* '2': ['ab']
* })
*
* @since 2.5.0
*/
export const groupBy =
<A>(f: (a: A) => string) =>
(as: ReadonlyArray<A>): ReadonlyRecord<string, ReadonlyNonEmptyArray<A>> => {
const out: Record<string, NonEmptyArray<A>> = {}
for (const a of as) {
const k = f(a)
if (_.has.call(out, k)) {
out[k].push(a)
} else {
out[k] = [a]
}
}
return out
}
/**
* @since 2.5.0
*/
export const sort =
<B>(O: Ord<B>) =>
<A extends B>(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> =>
as.length === 1 ? as : (as.slice().sort(O.compare) as any)
/**
* @since 2.5.0
*/
export const updateAt = <A>(i: number, a: A): ((as: ReadonlyNonEmptyArray<A>) => Option<ReadonlyNonEmptyArray<A>>) =>
modifyAt(i, () => a)
/**
* @since 2.5.0
*/
export const modifyAt =
<A>(i: number, f: (a: A) => A) =>
(as: ReadonlyNonEmptyArray<A>): Option<ReadonlyNonEmptyArray<A>> =>
isOutOfBound(i, as) ? _.none : _.some(unsafeUpdateAt(i, f(as[i]), as))
/**
* @since 2.5.1
*/
export const zipWith = <A, B, C>(
as: ReadonlyNonEmptyArray<A>,
bs: ReadonlyNonEmptyArray<B>,
f: (a: A, b: B) => C
): ReadonlyNonEmptyArray<C> => {
const cs: NonEmptyArray<C> = [f(as[0], bs[0])]
const len = Math.min(as.length, bs.length)
for (let i = 1; i < len; i++) {
cs[i] = f(as[i], bs[i])
}
return cs
}
/**
* @since 2.5.1
*/
export function zip<B>(
bs: ReadonlyNonEmptyArray<B>
): <A>(as: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<readonly [A, B]>
export function zip<A, B>(
as: ReadonlyNonEmptyArray<A>,
bs: ReadonlyNonEmptyArray<B>
): ReadonlyNonEmptyArray<readonly [A, B]>
export function zip<A, B>(
as: ReadonlyNonEmptyArray<A>,
bs?: ReadonlyNonEmptyArray<B>
): ReadonlyNonEmptyArray<readonly [A, B]> | ((bs: ReadonlyNonEmptyArray<B>) => ReadonlyNonEmptyArray<readonly [B, A]>) {
if (bs === undefined) {
return (bs) => zip(bs, as)
}
return zipWith(as, bs, (a, b) => [a, b])
}
/**
* @since 2.5.1
*/
export const unzip = <A, B>(
abs: ReadonlyNonEmptyArray<readonly [A, B]>
): readonly [ReadonlyNonEmptyArray<A>, ReadonlyNonEmptyArray<B>] => {
const fa: NonEmptyArray<A> = [abs[0][0]]
const fb: NonEmptyArray<B> = [abs[0][1]]
for (let i = 1; i < abs.length; i++) {
fa[i] = abs[i][0]
fb[i] = abs[i][1]
}
return [fa, fb]
}
/**
* Prepend an element to every member of a `ReadonlyNonEmptyArray`.
*
* @example
* import { prependAll } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(prependAll(9)([1, 2, 3, 4]), [9, 1, 9, 2, 9, 3, 9, 4])
*
* @since 2.10.0
*/
export const prependAll =
<A>(middle: A) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> => {
const out: NonEmptyArray<A> = [middle, as[0]]
for (let i = 1; i < as.length; i++) {
out.push(middle, as[i])
}
return out
}
/**
* Places an element in between members of a `ReadonlyNonEmptyArray`.
*
* @example
* import { intersperse } from 'fp-ts/ReadonlyNonEmptyArray'
*
* assert.deepStrictEqual(intersperse(9)([1, 2, 3, 4]), [1, 9, 2, 9, 3, 9, 4])
*
* @since 2.9.0
*/
export const intersperse =
<A>(middle: A) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A> => {
const rest = tail(as)
return isNonEmpty(rest) ? pipe(rest, prependAll(middle), prepend(head(as))) : as
}
/**
* @category sequencing
* @since 2.10.0
*/
export const chainWithIndex =
<A, B>(f: (i: number, a: A) => ReadonlyNonEmptyArray<B>) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<B> => {
const out: NonEmptyArray<B> = _.fromReadonlyNonEmptyArray(f(0, head(as)))
for (let i = 1; i < as.length; i++) {
const bs = f(i, as[i])
for (let j = 0; j < bs.length; j++) {
out.push(bs[j])
}
}
return out
}
/**
* A useful recursion pattern for processing a `ReadonlyNonEmptyArray` to produce a new `ReadonlyNonEmptyArray`, often used for "chopping" up the input
* `ReadonlyNonEmptyArray`. Typically `chop` is called with some function that will consume an initial prefix of the `ReadonlyNonEmptyArray` and produce a
* value and the tail of the `ReadonlyNonEmptyArray`.
*
* @since 2.10.0
*/
export const chop =
<A, B>(f: (as: ReadonlyNonEmptyArray<A>) => readonly [B, ReadonlyArray<A>]) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<B> => {
const [b, rest] = f(as)
const out: NonEmptyArray<B> = [b]
let next: ReadonlyArray<A> = rest
while (isNonEmpty(next)) {
const [b, rest] = f(next)
out.push(b)
next = rest
}
return out
}
/**
* Splits a `ReadonlyNonEmptyArray` into two pieces, the first piece has max `n` elements.
*
* @since 2.10.0
*/
export const splitAt =
(n: number) =>
<A>(as: ReadonlyNonEmptyArray<A>): readonly [ReadonlyNonEmptyArray<A>, ReadonlyArray<A>] => {
const m = Math.max(1, n)
return m >= as.length ? [as, empty] : [pipe(as.slice(1, m), prepend(head(as))), as.slice(m)]
}
/**
* Splits a `ReadonlyNonEmptyArray` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of
* the `ReadonlyNonEmptyArray`.
*
* @since 2.10.0
*/
export const chunksOf = (
n: number
): (<A>(as: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<ReadonlyNonEmptyArray<A>>) => chop(splitAt(n))
const _map: Functor1<URI>['map'] = (fa, f) => pipe(fa, map(f))
/* istanbul ignore next */
const _mapWithIndex: FunctorWithIndex1<URI, number>['mapWithIndex'] = (fa, f) => pipe(fa, mapWithIndex(f))
const _ap: Apply1<URI>['ap'] = (fab, fa) => pipe(fab, ap(fa))
/* istanbul ignore next */
const _extend: Extend1<URI>['extend'] = (wa, f) => pipe(wa, extend(f))
/* istanbul ignore next */
const _reduce: Foldable1<URI>['reduce'] = (fa, b, f) => pipe(fa, reduce(b, f))
/* istanbul ignore next */
const _foldMap: Foldable1<URI>['foldMap'] = (M) => {
const foldMapM = foldMap(M)
return (fa, f) => pipe(fa, foldMapM(f))
}
/* istanbul ignore next */
const _reduceRight: Foldable1<URI>['reduceRight'] = (fa, b, f) => pipe(fa, reduceRight(b, f))
/* istanbul ignore next */
const _traverse: Traversable1<URI>['traverse'] = <F>(
F: ApplicativeHKT<F>
): (<A, B>(ta: ReadonlyNonEmptyArray<A>, f: (a: A) => HKT<F, B>) => HKT<F, ReadonlyNonEmptyArray<B>>) => {
const traverseF = traverse(F)
return (ta, f) => pipe(ta, traverseF(f))
}
/* istanbul ignore next */
const _alt: Alt1<URI>['alt'] = (fa, that) => pipe(fa, alt(that))
/* istanbul ignore next */
const _reduceWithIndex: FoldableWithIndex1<URI, number>['reduceWithIndex'] = (fa, b, f) =>
pipe(fa, reduceWithIndex(b, f))
/* istanbul ignore next */
const _foldMapWithIndex: FoldableWithIndex1<URI, number>['foldMapWithIndex'] = (M) => {
const foldMapWithIndexM = foldMapWithIndex(M)
return (fa, f) => pipe(fa, foldMapWithIndexM(f))
}
/* istanbul ignore next */
const _reduceRightWithIndex: FoldableWithIndex1<URI, number>['reduceRightWithIndex'] = (fa, b, f) =>
pipe(fa, reduceRightWithIndex(b, f))
/* istanbul ignore next */
const _traverseWithIndex: TraversableWithIndex1<URI, number>['traverseWithIndex'] = <F>(
F: ApplicativeHKT<F>
): (<A, B>(ta: ReadonlyNonEmptyArray<A>, f: (i: number, a: A) => HKT<F, B>) => HKT<F, ReadonlyNonEmptyArray<B>>) => {
const traverseWithIndexF = traverseWithIndex(F)
return (ta, f) => pipe(ta, traverseWithIndexF(f))
}
/**
* @category constructors
* @since 2.5.0
*/
export const of: <A>(a: A) => ReadonlyNonEmptyArray<A> = _.singleton
/**
* Less strict version of [`alt`](#alt).
*
* The `W` suffix (short for **W**idening) means that the return types will be merged.
*
* @example
* import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(
* pipe(
* [1, 2, 3] as RNEA.ReadonlyNonEmptyArray<number>,
* RNEA.altW(() => ['a', 'b'])
* ),
* [1, 2, 3, 'a', 'b']
* )
*
* @category error handling
* @since 2.9.0
*/
export const altW =
<B>(that: LazyArg<ReadonlyNonEmptyArray<B>>) =>
<A>(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<A | B> =>
pipe(as, concatW(that()))
/**
* Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to
* types of kind `* -> *`.
*
* In case of `ReadonlyNonEmptyArray` concatenates the inputs into a single array.
*
* @example
* import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(
* pipe(
* [1, 2, 3],
* RNEA.alt(() => [4, 5])
* ),
* [1, 2, 3, 4, 5]
* )
*
* @category error handling
* @since 2.6.2
*/
export const alt: <A>(
that: LazyArg<ReadonlyNonEmptyArray<A>>
) => (as: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<A> = altW
/**
* @since 2.5.0
*/
export const ap = <A>(
as: ReadonlyNonEmptyArray<A>
): (<B>(fab: ReadonlyNonEmptyArray<(a: A) => B>) => ReadonlyNonEmptyArray<B>) => flatMap((f) => pipe(as, map(f)))
/**
* @example
* import * as RNEA from 'fp-ts/ReadonlyNonEmptyArray'
* import { pipe } from 'fp-ts/function'
*
* assert.deepStrictEqual(
* pipe(
* [1, 2, 3],
* RNEA.flatMap((n) => [`a${n}`, `b${n}`])
* ),
* ['a1', 'b1', 'a2', 'b2', 'a3', 'b3']
* )
*
* @category sequencing
* @since 2.14.0
*/
export const flatMap: {
<A, B>(f: (a: A, i: number) => ReadonlyNonEmptyArray<B>): (ma: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<B>
<A, B>(ma: ReadonlyNonEmptyArray<A>, f: (a: A, i: number) => ReadonlyNonEmptyArray<B>): ReadonlyNonEmptyArray<B>
} = /*#__PURE__*/ dual(
2,
<A, B>(ma: ReadonlyNonEmptyArray<A>, f: (a: A, i: number) => ReadonlyNonEmptyArray<B>): ReadonlyNonEmptyArray<B> =>
pipe(
ma,
chainWithIndex((i, a) => f(a, i))
)
)
/**
* @since 2.5.0
*/
export const extend =
<A, B>(f: (as: ReadonlyNonEmptyArray<A>) => B) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<B> => {
let next: ReadonlyArray<A> = tail(as)
const out: NonEmptyArray<B> = [f(as)]
while (isNonEmpty(next)) {
out.push(f(next))
next = tail(next)
}
return out
}
/**
* @since 2.5.0
*/
export const duplicate: <A>(ma: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<ReadonlyNonEmptyArray<A>> =
/*#__PURE__*/ extend(identity)
/**
* @category sequencing
* @since 2.5.0
*/
export const flatten: <A>(mma: ReadonlyNonEmptyArray<ReadonlyNonEmptyArray<A>>) => ReadonlyNonEmptyArray<A> =
/*#__PURE__*/ flatMap(identity)
/**
* `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
* use the type constructor `F` to represent some computational context.
*
* @category mapping
* @since 2.5.0
*/
export const map = <A, B>(f: (a: A) => B): ((as: ReadonlyNonEmptyArray<A>) => ReadonlyNonEmptyArray<B>) =>
mapWithIndex((_, a) => f(a))
/**
* @category mapping
* @since 2.5.0
*/
export const mapWithIndex =
<A, B>(f: (i: number, a: A) => B) =>
(as: ReadonlyNonEmptyArray<A>): ReadonlyNonEmptyArray<B> => {
const out: NonEmptyArray<B> = [f(0, head(as))]
for (let i = 1; i < as.length; i++) {
out.push(f(i, as[i]))
}
return out
}
/**
* @category folding
* @since 2.5.0
*/
export const reduce = <A, B>(b: B, f: (b: B, a: A) => B): ((as: ReadonlyNonEmptyArray<A>) => B) =>
reduceWithIndex(b, (_, b, a) => f(b, a))
/**
* **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`.
*
* @category folding
* @since 2.5.0
*/
export const foldMap =
<S>(S: Semigroup<S>) =>
<A>(f: (a: A) => S) =>
(as: ReadonlyNonEmptyArray<A>): S =>
as.slice(1).reduce((s, a) => S.concat(s, f(a)), f(as[0]))
/**
* @category folding
* @since 2.5.0
*/
export const reduceRight = <A, B>(b: B, f: (a: A, b: B) => B): ((as: ReadonlyNonEmptyArray<A>) => B) =>
reduceRightWithIndex(b, (_, b, a) => f(b, a))
/**
* @category folding
* @since 2.5.0
*/
export const reduceWithIndex =
<A, B>(b: B, f: (i: number, b: B, a: A) => B) =>
(as: ReadonlyNonEmptyArray<A>): B =>
as.reduce((b, a, i) => f(i, b, a), b)
/**
* **Note**. The constraint is relaxed: a `Semigroup` instead of a `Monoid`.
*
* @category folding
* @since 2.5.0
*/
export const foldMapWithIndex =
<S>(S: Semigroup<S>) =>
<A>(f: (i: number, a: A) => S) =>
(as: ReadonlyNonEmptyArray<A>): S =>
as.slice(1).reduce((s, a, i) => S.concat(s, f(i + 1, a)), f(0, as[0]))
/**
* @category folding
* @since 2.5.0
*/
export const reduceRightWithIndex =
<A, B>(b: B, f: (i: number, a: A, b: B) => B) =>
(as: ReadonlyNonEmptyArray<A>): B =>
as.reduceRight((b, a, i) => f(i, a, b), b)
/**
* @category traversing
* @since 2.6.3
*/
export const traverse: PipeableTraverse1<URI> = <F>(
F: ApplicativeHKT<F>
): (<A, B>(f: (a: A) => HKT<F, B>) => (as: ReadonlyNonEmptyArray<A>) => HKT<F, ReadonlyNonEmptyArray<B>>) => {
const traverseWithIndexF = traverseWithIndex(F)
return (f) => traverseWithIndexF((_, a) => f(a))
}
/**
* @category traversing
* @since 2.6.3
*/
export const sequence: Traversable1<URI>['sequence'] = <F>(
F: ApplicativeHKT<F>
): (<A>(as: ReadonlyNonEmptyArray<HKT<F, A>>) => HKT<F, ReadonlyNonEmptyArray<A>>) => traverseWithIndex(F)(SK)
/**
* @category sequencing
* @since 2.6.3
*/
export const traverseWithIndex: PipeableTraverseWithIndex1<URI, number> =
<F>(F: ApplicativeHKT<F>) =>
<A, B>(f: (i: number, a: A) => HKT<F, B>) =>
(as: ReadonlyNonEmptyArray<A>): HKT<F, ReadonlyNonEmptyArray<B>> => {
let out: HKT<F, ReadonlyNonEmptyArray<B>> = F.map(f(0, head(as)), of)
for (let i = 1; i < as.length; i++) {
out = F.ap(
F.map(out, (bs) => (b: B) => pipe(bs, append(b))),
f(i, as[i])
)
}
return out
}
/**
* @category Comonad
* @since 2.6.3
*/
export const extract: Comonad1<URI>['extract'] = _.head
/**
* @category type lambdas
* @since 2.5.0
*/
export const URI = 'ReadonlyNonEmptyArray'
/**
* @category type lambdas
* @since 2.5.0
*/
export type URI = typeof URI
declare module './HKT' {
interface URItoKind<A> {
readonly [URI]: ReadonlyNonEmptyArray<A>
}
}
/**
* @category instances
* @since 2.5.0
*/
export const getShow = <A>(S: Show<A>): Show<ReadonlyNonEmptyArray<A>> => ({
show: (as) => `[${as.map(S.show).join(', ')}]`
})
/**
* Builds a `Semigroup` instance for `ReadonlyNonEmptyArray`
*
* @category instances
* @since 2.5.0
*/
export const getSemigroup = <A = never>(): Semigroup<ReadonlyNonEmptyArray<A>> => ({
concat
})
/**
* @example
* import { getEq } from 'fp-ts/ReadonlyNonEmptyArray'
* import * as N from 'fp-ts/number'
*
* const E = getEq(N.Eq)
* assert.strictEqual(E.equals([1, 2], [1, 2]), true)
* assert.strictEqual(E.equals([1, 2], [1, 3]), false)
*
* @category instances
* @since 2.5.0
*/
export const getEq = <A>(E: Eq<A>): Eq<ReadonlyNonEmptyArray<A>> =>
fromEquals((xs, ys) => xs.length === ys.length && xs.every((x, i) => E.equals(x, ys[i])))
/**
* @since 2.11.0
*/
export const getUnionSemigroup = <A>(E: Eq<A>): Semigroup<ReadonlyNonEmptyArray<A>> => {
const unionE = union(E)
return {
concat: (first, second) => unionE(second)(first)
}
}
/**
* @category instances
* @since 2.7.0
*/
export const Functor: Functor1<URI> = {
URI,
map: _map
}
/**
* @category mapping
* @since 2.10.0
*/
export const flap = /*#__PURE__*/ flap_(Functor)
/**
* @category instances
* @since 2.10.0
*/
export const Pointed: Pointed1<URI> = {
URI,
of
}
/**
* @category instances
* @since 2.7.0
*/
export const FunctorWithIndex: FunctorWithIndex1<URI, number> = {
URI,
map: _map,
mapWithIndex: _mapWithIndex
}
/**
* @category instances