Skip to content

Commit

Permalink
Merge pull request #7 from shubhamgautam89/pattern/observer
Browse files Browse the repository at this point in the history
observer patternn
  • Loading branch information
shubhamgautam89 committed Oct 16, 2023
2 parents 26dacc4 + ea6bd56 commit 52f6a5e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
23 changes: 23 additions & 0 deletions patterns/observer/observer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* With the observer pattern, we can subscribe certain objects, the observers, to another object, called the observable. Whenever an event occurs, the observable notifies all its observers!
*/

class Observable {
constructor() {
this.observers = [];
}

subscribe(f) {
this.observers.push(f);
}

unsubscribe(f) {
this.observers = this.observers.filter((subs) => subs !== f);
}

notify(data) {
this.observers.forEach((observer) => observer(data));
}
}

export default Observable;
37 changes: 37 additions & 0 deletions patterns/observer/observer.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Observable from "./observer";

describe("Observable", () => {
let observable;
beforeEach(() => {
observable = new Observable();
});

test("subscribes a function and notiofies it", () => {
const mockFunction = jest.fn();
observable.subscribe(mockFunction);
observable.notify("test-data");

expect(mockFunction).toHaveBeenCalledWith("test-data");
});

test("unsubscirbes a function and does not notify it", () => {
const mockFunction = jest.fn();
observable.subscribe(mockFunction);
observable.unsubscribe(mockFunction);

observable.notify("test-data");

expect(mockFunction).not.toHaveBeenCalled();
});

test("notifies only subscribed function", () => {
const mockFunction1 = jest.fn();
const mockFunction2 = jest.fn();

observable.subscribe(mockFunction1);
observable.notify("test-data");

expect(mockFunction1).toHaveBeenCalledWith("test-data");
expect(mockFunction2).not.toHaveBeenCalled();
});
});

0 comments on commit 52f6a5e

Please sign in to comment.