-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmonad-class.js
More file actions
77 lines (62 loc) · 1.36 KB
/
monad-class.js
File metadata and controls
77 lines (62 loc) · 1.36 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
'use strict';
class Point {
#x;
#y;
constructor(x, y) {
const errors = Point.validate(x, y);
if (errors.length > 0) {
const cause = new AggregateError(errors, 'Validation');
throw new RangeError('Bad coordinates', { cause });
}
this.#x = x;
this.#y = y;
}
static validate(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;
}
static of(x, y) {
return new Point(x, y);
}
map(fn) {
const { x, y } = fn(this.#x, this.#y);
return Point.of(x, y);
}
chain(fn) {
return fn(this.#x, this.#y);
}
}
class PointTransform {
constructor(fn) {
this.fn = fn;
}
ap(point) {
return point.map(this.fn);
}
}
class Serialized {
#data;
constructor(data) {
this.#data = data;
}
map(fn) {
fn(this.#data);
return this;
}
tap(fn) {
fn(this.#data);
return this;
}
}
const move = (dx, dy) => (x, y) => ({ x: x + dx, y: y + dy });
const clone = (x, y) => ({ x, y });
const toString = (x, y) => new Serialized(`(${x}, ${y})`);
// Usage
const p1 = Point.of(10, 20);
p1.chain(toString).tap(console.log);
const c0 = p1.map(clone);
const t1 = new PointTransform(move(-5, 10));
const c1 = t1.ap(c0);
c1.chain(toString).tap(console.log);