-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathfp-compose.js
More file actions
32 lines (25 loc) · 914 Bytes
/
fp-compose.js
File metadata and controls
32 lines (25 loc) · 914 Bytes
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
'use strict';
const pipe = (...fns) => (obj) => fns.reduce((val, f) => f(val), obj);
// Implementation
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;
};
const createPoint = (x) => (y) => {
const errors = validatePoint(x, y);
if (errors.length > 0) {
const cause = new AggregateError(errors, 'Validation');
throw new RangeError('Bad coordinates', { cause });
}
return { map: (f) => f({ x, y }) };
};
const move = (dx) => (dy) => ({ x, y }) => ({ x: x + dx, y: y + dy });
const clone = ({ x, y }) => ({ x, y });
const toString = ({ x, y }) => `(${x}, ${y})`;
// Usage
const p1 = createPoint(10)(20);
console.log(p1.map(toString));
const operations = pipe(clone, move(-5)(10), toString, console.log);
p1.map(operations);