Skip to content

Commit

Permalink
refactor: add an AbstractSubject that implements Subject
Browse files Browse the repository at this point in the history
  • Loading branch information
Flowrey committed Sep 8, 2024
1 parent e891525 commit 730e4d1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 28 deletions.
31 changes: 3 additions & 28 deletions src/js/teaching_unit/model.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import { Observer, Subject } from "../utils";
import { AbstractSubject } from "../utils";

export enum State {
Unselected,
Selected,
Validated,
}

export class TeachingUnit implements Subject {
export class TeachingUnit extends AbstractSubject {
public title: string;
public code: string;
public ects: number;
public state: State;

private observers: Observer[] = [];

constructor(title: string, code: string, ects: number, state?: State) {
super();
this.title = title;
this.code = code;
this.ects = ects;
Expand Down Expand Up @@ -44,30 +43,6 @@ export class TeachingUnit implements Subject {
);
}

public attach(observer: Observer): void {
const isExist = this.observers.includes(observer);
if (isExist) {
throw new Error("Observer has been attached already");
}

this.observers.push(observer);
}

public detach(observer: Observer): void {
const observerIndex = this.observers.indexOf(observer);
if (observerIndex === -1) {
throw new Error("Nonexistent observer");
}

this.observers.splice(observerIndex, 1);
}

public notify(): void {
for (const observer of this.observers) {
observer.update(this);
}
}

public toggle() {
switch (this.state) {
case State.Unselected:
Expand Down
28 changes: 28 additions & 0 deletions src/js/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,31 @@ export interface Subject {
export interface Observer {
update(subject: Subject): void;
}

export abstract class AbstractSubject implements Subject {
private observers: Observer[] = [];

public attach(observer: Observer): void {
const isExist = this.observers.includes(observer);
if (isExist) {
throw new Error("Observer has been attached already");
}

this.observers.push(observer);
}

public detach(observer: Observer): void {
const observerIndex = this.observers.indexOf(observer);
if (observerIndex === -1) {
throw new Error("Nonexistent observer");
}

this.observers.splice(observerIndex, 1);
}

public notify(): void {
for (const observer of this.observers) {
observer.update(this);
}
}
}

0 comments on commit 730e4d1

Please sign in to comment.