-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathevent-closure.js
More file actions
41 lines (34 loc) · 1.03 KB
/
event-closure.js
File metadata and controls
41 lines (34 loc) · 1.03 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
'use strict';
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 });
}
const move = (d) => {
x += d.x;
y += d.y;
};
const clone = () => createPoint({ x, y });
const toString = () => `(${x}, ${y})`;
const events = { move, clone, toString };
const emit = (eventName, args) => {
const event = events[eventName];
if (!event) throw new Error(`Unknown event: ${event}`);
return event(args);
};
return { emit };
};
// Usage
const p1 = createPoint({ x: 10, y: 20 });
console.log(p1.emit('toString'));
const c1 = p1.emit('clone');
console.log(c1.emit('toString'));
c1.emit('move', { x: -5, y: 10 });
console.log(c1.emit('toString'));