-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathemitter-sync-pattern.ts
More file actions
89 lines (65 loc) · 2.4 KB
/
emitter-sync-pattern.ts
File metadata and controls
89 lines (65 loc) · 2.4 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
80
81
82
83
84
85
86
87
88
89
/* Check the comments first */
import { EventEmitter } from "./emitter";
import { EventDelayedRepository } from "./event-repository";
import { EventStatistics } from "./event-statistics";
import { ResultsTester } from "./results-tester";
import { triggerRandomly } from "./utils";
const MAX_EVENTS = 1000;
enum EventName {
EventA = "A",
EventB = "B",
}
const EVENT_NAMES = [EventName.EventA, EventName.EventB];
/*
An initial configuration for this case
*/
function init() {
const emitter = new EventEmitter<EventName>();
triggerRandomly(() => emitter.emit(EventName.EventA), MAX_EVENTS);
triggerRandomly(() => emitter.emit(EventName.EventB), MAX_EVENTS);
const repository = new EventRepository();
const handler = new EventHandler(emitter, repository);
const resultsTester = new ResultsTester({
eventNames: EVENT_NAMES,
emitter,
handler,
repository,
});
resultsTester.showStats(20);
}
/* Please do not change the code above this line */
/* ----–––––––––––––––––––––––––––––––––––––---- */
/*
The implementation of EventHandler and EventRepository is up to you.
Main idea is to subscribe to EventEmitter, save it in local stats
along with syncing with EventRepository.
The implementation of EventHandler and EventRepository is flexible and left to your discretion.
The primary objective is to subscribe to EventEmitter, record the events in `.eventStats`,
and ensure synchronization with EventRepository.
The ultimate aim is to have the `.eventStats` of EventHandler and EventRepository
have the same values (and equal to the actual events fired by the emitter) by the
time MAX_EVENTS have been fired.
*/
class EventHandler extends EventStatistics<EventName> {
// Feel free to edit this class
repository: EventRepository;
constructor(emitter: EventEmitter<EventName>, repository: EventRepository) {
super();
this.repository = repository;
emitter.subscribe(EventName.EventA, () =>
this.repository.saveEventData(EventName.EventA, 1)
);
}
}
class EventRepository extends EventDelayedRepository<EventName> {
// Feel free to edit this class
async saveEventData(eventName: EventName, _: number) {
try {
await this.updateEventStatsBy(eventName, 1);
} catch (e) {
// const _error = e as EventRepositoryError;
// console.warn(error);
}
}
}
init();