-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy path9-spaghetti.js
77 lines (61 loc) · 1.56 KB
/
9-spaghetti.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
// Antipattern: Spaghetti code
// - JMP, GOTO
// - Callbacks
// - Events
// - Promises
// Callbacks
{
const invoke = (validate, fn, a, b, callback) => {
const result = fn(validate, a, b);
callback(null, result);
};
const max = (validate, a, b) => {
let valid = true;
const conjunction = (err, res) => {
valid = valid && res;
};
validate(a, conjunction);
validate(b, conjunction);
if (!valid) throw new TypeError('Unexpected parameter');
return Math.max(a, b);
};
const isNumber = (value, callback) => {
const valid = typeof value === 'number';
callback(null, valid);
};
invoke(isNumber, max, 10, 20, (err, result) => {
console.dir({ result });
});
}
// Events
// Try to debug this code to find logical error
{
const { EventEmitter } = require('node:events');
const incoming = new EventEmitter();
const controller = new EventEmitter();
const processing = new EventEmitter();
const parameters = [];
incoming.on('return', (result) => {
console.dir({ result });
});
processing.on('max', (a, b) => {
incoming.emit('return', Math.max(a, b));
});
controller.on('parameter', (value) => {
parameters.push(value);
});
incoming.on('input', (data) => {
if (typeof data === 'string') {
controller.emit('call', data);
} else {
controller.emit('parameter', data);
}
});
controller.on('call', (name) => {
processing.emit(name, ...parameters);
});
incoming.emit('input', 10);
incoming.emit('input', 20);
incoming.emit('input', 'max');
}