-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path7-either.js
60 lines (45 loc) · 1.03 KB
/
7-either.js
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
'use strict';
class Either {
#left = null;
#right = null;
constructor({ left = null, right = null }) {
this.#left = left;
this.#right = right;
}
static left(value) {
return new Either({ left: value, right: null });
}
static right(value) {
return new Either({ left: null, right: value });
}
get left() {
return this.#left;
}
get right() {
return this.#right;
}
isLeft() {
return this.#left !== null;
}
isRight() {
return this.#right !== null;
}
map(fn) {
if (this.#right === null) return this;
return Either.right(fn(this.#right));
}
match(leftFn, rightFn) {
const isRight = this.#right !== null;
return isRight ? rightFn(this.#right) : leftFn(this.#left);
}
}
// Usage
const success = Either.right(42);
const failure = Either.left(500);
const doubled = success.map((x) => x * 2);
console.log({ doubled: doubled.right });
const result = failure.match(
(error) => `Failure: ${error}`,
(value) => `Success: ${value}`,
);
console.log({ result });