Skip to content

UndirectedGraph<T> / DirectedGraph<T> ​

Guide: /guide/data-structures/graph

Generic Types ​

T - type of collection elements

Implements interfaces ​

IGraph ​

Properties ​

adjacencyList: ReadonlyMap<T, ReadonlySet<T>> ​

Read-only access to the graph's adjacency list as a map of vertices to their neighbors.

Methods ​

constructor(params?: TGraphConstructorParams<T>): IGraph<T> ​

Creates empty instance with optional custom key selector.

Params: ​
NameTypeRequiredDefaultDescription
paramsTGraphConstructorParams<T>--Optional parameters including custom key selector



weight(): number ​

Sum of all edges in graph



vertices(): Array<T> ​

Only vertices itself without edges and weight info



verticesCount(): number ​

Count of vertices



edgesCount(): number ​

Count of all edges (it's different in directed and undirected graphs)



addVertex(value: T): IGraph<T> ​

Create new graph node

Params: ​
NameTypeRequiredDefaultDescription
valueT+-
Throws: IsAlreadyExistsException when vertex is already exists ​



hasVertex(value: T): boolean ​

Check if graph has given vertex

Params: ​
NameTypeRequiredDefaultDescription
valueT+-



getVertexKey(data: T): string ​

Get the string key representation of a vertex using the key selector function.

Params: ​
NameTypeRequiredDefaultDescription
dataT+-The vertex data to get key for



getVertexNeighbors(data: T): Set<T> ​

Get the set of neighboring vertices for a given vertex.

Params: ​
NameTypeRequiredDefaultDescription
dataT+-The vertex data to get neighbors for
Throws: IsNotFoundException when vertex is not found ​



addEdge(from: T, to: T, weight?: number): IGraph<T> ​

Add new edge between two given vertices

Params: ​
NameTypeRequiredDefaultDescription
fromT+-Start vertex
toT+-End vertex
weightnumber-0Edge weight
Throws: IsNotFoundException when one of vertices was not found ​

Difference between directed and undirected graphs

In case of undirected graph, edges A->B and B->A are the same
Instead, in case of directed graph, they are not equal

When edge already exists

In case of already existed edge, its weight just will be updated



removeEdge(from: T, to: T): IGraph<T> ​

Remove edge between two given vertices

Params: ​
NameTypeRequiredDefaultDescription
fromT+-Start vertex
toT+-End vertex
Throws: IsNotFoundException when edge to remove was not found ​



hasEdge(from: T, to: T): boolean ​

Check if graph has edge between two given vertices

Params: ​
NameTypeRequiredDefaultDescription
fromT+-Start vertex
toT+-End vertex



getEdgeWeight(from: T, to: T): number ​

Get weight of edge between two given vertices

Params: ​
NameTypeRequiredDefaultDescription
fromT+-Start vertex
toT+-End vertex





removeVertex(data: T): IGraph<T> ​

Remove a vertex and all its connected edges from the graph.

Params: ​
NameTypeRequiredDefaultDescription
dataT+-The vertex data to remove
Throws: IsNotFoundException when vertex to remove was not found ​

MIT Licensed