forked from gcanti/fp-ts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayOption.ts
76 lines (61 loc) · 1.99 KB
/
ArrayOption.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
import { array } from '../src/Array'
import { Monad1 } from '../src/Monad'
import { Option } from '../src/Option'
import * as optionT from '../src/OptionT'
declare module '../src/HKT' {
interface URI2HKT<A> {
ArrayOption: ArrayOption<A>
}
}
const optionTArray = optionT.getOptionT(array)
export const URI = 'ArrayOption'
export type URI = typeof URI
const optionTfold = optionT.fold(array)
export class ArrayOption<A> {
readonly _A!: A
readonly _URI!: URI
constructor(readonly value: Array<Option<A>>) {}
map<B>(f: (a: A) => B): ArrayOption<B> {
return new ArrayOption(optionTArray.map(this.value, f))
}
ap<B>(fab: ArrayOption<(a: A) => B>): ArrayOption<B> {
return new ArrayOption(optionTArray.ap<A, B>(fab.value, this.value))
}
ap_<B, C>(this: ArrayOption<(b: B) => C>, fb: ArrayOption<B>): ArrayOption<C> {
return fb.ap(this)
}
chain<B>(f: (a: A) => ArrayOption<B>): ArrayOption<B> {
return new ArrayOption(optionTArray.chain(a => f(a).value, this.value))
}
fold<R>(r: R, some: (a: A) => R): Array<R> {
return optionTfold(r, some, this.value)
}
}
const map = <A, B>(fa: ArrayOption<A>, f: (a: A) => B): ArrayOption<B> => {
return fa.map(f)
}
const optionTsome = optionT.some(array)
const of = <A>(a: A): ArrayOption<A> => {
return new ArrayOption(optionTsome(a))
}
const ap = <A, B>(fab: ArrayOption<(a: A) => B>, fa: ArrayOption<A>): ArrayOption<B> => {
return fa.ap(fab)
}
const chain = <A, B>(fa: ArrayOption<A>, f: (a: A) => ArrayOption<B>): ArrayOption<B> => {
return fa.chain(f)
}
export const some = of
export const none = new ArrayOption(optionT.none(array)())
const optionTfromOption = optionT.fromOption(array)
export const fromOption = <A>(oa: Option<A>): ArrayOption<A> => {
return new ArrayOption(optionTfromOption(oa))
}
const optionTliftF = optionT.liftF(array)
export const fromArray = <A>(ma: Array<A>): ArrayOption<A> => new ArrayOption(optionTliftF(ma))
export const arrayOption: Monad1<URI> = {
URI,
map,
of,
ap,
chain
}