-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmonad-result.js
More file actions
79 lines (63 loc) · 1.68 KB
/
monad-result.js
File metadata and controls
79 lines (63 loc) · 1.68 KB
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
'use strict';
class Result {
#value = null;
#error = null;
constructor(value, error) {
this.#value = value;
this.#error = error;
}
static value(value) {
return new Result(value, null);
}
static ok(value) {
return Result.value(value);
}
static error(error) {
return new Result(null, error);
}
map(fn) {
return this.#error ? this : Result.ok(fn(this.#value));
}
chain(fn) {
return this.#error ? this : fn(this.#value);
}
ap(container) {
if (this.#error) return this;
if (container.#error) return container;
return Result.ok(this.#value(container.#value));
}
bimap(success, fail) {
if (this.#error) return Result.ok(fail(this.#error));
return Result.ok(success(this.#value));
}
get value() {
return this.#value;
}
get error() {
return this.#error;
}
tap(fn) {
fn(this.#value);
return this;
}
}
const validatePoint = ({ x, y }) => {
const errors = [];
if (!Number.isFinite(x)) errors.push(new TypeError(`Invalid x: ${x}`));
if (!Number.isFinite(y)) errors.push(new TypeError(`Invalid y: ${y}`));
return errors.length > 0
? Result.error(new AggregateError(errors, 'Validation'))
: Result.ok({ x, y });
};
const move = (d) => (p) => ({ x: p.x + d.x, y: p.y + d.y });
const clone = ({ x, y }) => ({ x, y });
const toString = ({ x, y }) => `(${x}, ${y})`;
const id = (value) => value;
// Usage
const p1 = Result.ok({ x: 10, y: 20 }).chain(validatePoint);
p1.bimap(toString, id).tap(console.log);
const c0 = p1.map(clone);
const p2 = Result.ok({ x: -5, y: 10 }).chain(validatePoint);
const m1 = Result.ok(move).ap(p2);
const c1 = m1.ap(c0);
c1.bimap(toString, id).tap(console.log);