-
Notifications
You must be signed in to change notification settings - Fork 21
/
app.ts
116 lines (89 loc) · 2.57 KB
/
app.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// interfaces
interface IEvent {
type(): string;
machineId(): string;
}
interface ISubscriber {
handle(event: IEvent): void;
}
interface IPublishSubscribeService {
publish (event: IEvent): void;
subscribe (type: string, handler: ISubscriber): void;
// unsubscribe ( /* Question 2 - build this feature */ );
}
// implementations
class MachineSaleEvent implements IEvent {
constructor(private readonly _sold: number, private readonly _machineId: string) {}
machineId(): string {
return this._machineId;
}
getSoldQuantity(): number {
return this._sold
}
type(): string {
return 'sale';
}
}
class MachineRefillEvent implements IEvent {
constructor(private readonly _refill: number, private readonly _machineId: string) {}
machineId(): string {
throw new Error("Method not implemented.");
}
type(): string {
throw new Error("Method not implemented.");
}
}
class MachineSaleSubscriber implements ISubscriber {
public machines: Machine[];
constructor (machines: Machine[]) {
this.machines = machines;
}
handle(event: MachineSaleEvent): void {
this.machines[2].stockLevel -= event.getSoldQuantity();
}
}
class MachineRefillSubscriber implements ISubscriber {
handle(event: IEvent): void {
throw new Error("Method not implemented.");
}
}
// objects
class Machine {
public stockLevel = 10;
public id: string;
constructor (id: string) {
this.id = id;
}
}
// helpers
const randomMachine = (): string => {
const random = Math.random() * 3;
if (random < 1) {
return '001';
} else if (random < 2) {
return '002';
}
return '003';
}
const eventGenerator = (): IEvent => {
const random = Math.random();
if (random < 0.5) {
const saleQty = Math.random() < 0.5 ? 1 : 2; // 1 or 2
return new MachineSaleEvent(saleQty, randomMachine());
}
const refillQty = Math.random() < 0.5 ? 3 : 5; // 3 or 5
return new MachineRefillEvent(refillQty, randomMachine());
}
// program
(async () => {
// create 3 machines with a quantity of 10 stock
const machines: Machine[] = [ new Machine('001'), new Machine('002'), new Machine('003') ];
// create a machine sale event subscriber. inject the machines (all subscribers should do this)
const saleSubscriber = new MachineSaleSubscriber(machines);
// create the PubSub service
const pubSubService: IPublishSubscribeService = null as unknown as IPublishSubscribeService; // implement and fix this
// create 5 random events
const events = [1,2,3,4,5].map(i => eventGenerator());
// publish the events
events.map(pubSubService.publish);
})();