Skip to content

Commit

Permalink
Merge pull request #12 from diogofcunha/errors
Browse files Browse the repository at this point in the history
refactor: 💡started to use dedicated classes for errors
  • Loading branch information
diogofcunha authored Jan 18, 2024
2 parents 9d7a236 + 83788d7 commit ed77870
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
26 changes: 26 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
export class NodeNotFoundError extends Error {
constructor(nodeId: string) {
super(`Node ${nodeId} not found`);
}
}

export enum WeightedGraphEdgeErrorType {
ShouldProvideWeight,
ShouldNotProvideWeight
}

export class WeightedGraphEdgeError extends Error {
constructor(type: WeightedGraphEdgeErrorType) {
super(
type === WeightedGraphEdgeErrorType.ShouldProvideWeight
? `Can't add an edge to a weighted graph without weight`
: `Can't add an edge to a unweighted graph with weight`
);
}
}

export class GraphCycleError extends Error {
constructor() {
super(`Graph has a cycle`);
}
}
21 changes: 16 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import {
GraphCycleError,
NodeNotFoundError,
WeightedGraphEdgeError,
WeightedGraphEdgeErrorType
} from "./error";

export class Node<T> {
public incomingNeighbors: string[] = [];
constructor(public readonly id: string, public readonly value: T) {}
Expand Down Expand Up @@ -46,7 +53,7 @@ export class Graph<T> {
const nodeIdx = this._nodesById.get(nodeId);

if (nodeIdx === undefined) {
throw new Error(`Node ${nodeId} not found`);
throw new NodeNotFoundError(nodeId);
}

return this._nodes[nodeIdx];
Expand All @@ -59,11 +66,15 @@ export class Graph<T> {

addEdge(node1: Node<T>, node2: Node<T>, weight?: number) {
if (this.weighted && weight === undefined) {
throw new Error(`Can't add an edge to a weighted graph without weight`);
throw new WeightedGraphEdgeError(
WeightedGraphEdgeErrorType.ShouldProvideWeight
);
}

if (!this.weighted && weight !== undefined) {
throw new Error(`Can't add an edge to a unweighted graph with weight`);
throw new WeightedGraphEdgeError(
WeightedGraphEdgeErrorType.ShouldNotProvideWeight
);
}

this.getNodeById(node1);
Expand Down Expand Up @@ -102,7 +113,7 @@ export class Graph<T> {
const nodeIndex = this._nodesById.get(node.id);

if (nodeIndex === undefined) {
throw new Error(`Node ${node.id} not found`);
throw new NodeNotFoundError(node.id);
}

this._nodes.splice(nodeIndex, 1);
Expand Down Expand Up @@ -216,7 +227,7 @@ export class Graph<T> {
}

if (result.length !== this._nodes.length) {
throw new Error("Graph has a cycle");
throw new GraphCycleError();
}

return result;
Expand Down

0 comments on commit ed77870

Please sign in to comment.