Skip to content

Commit 1c78ffe

Browse files
committed
[ts] refator observer
1 parent de8c3d5 commit 1c78ffe

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

Diff for: observer-pattern/observer-pattern.ts

+25-13
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,21 @@ interface Observer {
2222
update(stocks: Object): void;
2323
}
2424

25-
class StockGrabber implements Subject {
26-
private observers: Array<Observer>;
27-
private stocks: Object;
25+
class DuplicateStockError extends Error {
26+
constructor(name: string) {
27+
super(`stock '${name}' already exists`);
28+
}
29+
}
2830

29-
constructor() {
30-
this.observers = new Array();
31-
this.stocks = new Array();
31+
class StockNotFoundError extends Error {
32+
constructor(name: string) {
33+
super(`stock '${name}' doens't exists`);
3234
}
35+
}
36+
37+
class StockGrabber implements Subject {
38+
private observers = new Array<Observer>();
39+
private stocks: Record<string, number> = {};
3340

3441
register(o: Observer): void {
3542
this.observers.push(o);
@@ -41,40 +48,45 @@ class StockGrabber implements Subject {
4148
}
4249

4350
notifyObservers(): void {
44-
this.observers.forEach(o => o.update(this.stocks));
51+
const stocksCopy = JSON.parse(JSON.stringify(this.stocks));
52+
this.observers.forEach((o) => o.update(stocksCopy));
4553
}
4654

4755
addStock(name: string, price: number) {
48-
if (this.stocks[name] !== undefined) throw new Error("key already exist");
56+
if (this.hasStock(name)) throw new DuplicateStockError(name);
4957

5058
this.stocks[name] = price;
5159
this.notifyObservers();
5260
}
5361

5462
removeStock(name: string) {
63+
if (!this.hasStock(name)) throw new StockNotFoundError(name);
64+
5565
delete this.stocks[name];
5666
this.notifyObservers();
5767
}
5868

5969
updateStock(name: string, price: number) {
60-
if (this.stocks[name] !== undefined) throw new Error("stock doesn't exist");
70+
if (!this.hasStock(name)) throw new StockNotFoundError(name);
6171

6272
this.stocks[name] = price;
6373
this.notifyObservers();
6474
}
75+
76+
private hasStock(name: string) {
77+
return name in this.stocks;
78+
}
6579
}
6680

6781
class StockObserver implements Observer {
68-
private stocks: Object;
69-
private grabber: StockGrabber;
82+
private stocks = new Object();
7083

7184
constructor(grabber: StockGrabber) {
72-
this.stocks = new Object();
73-
this.grabber = grabber;
7485
grabber.register(this);
7586
}
7687

7788
update(stocks: Object): void {
89+
console.log("got an update", { from: this.stocks, to: stocks });
7890
this.stocks = stocks;
7991
}
8092
}

0 commit comments

Comments
 (0)