es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
42 lines (41 loc) • 1.26 kB
JavaScript
/**
* Represents a graph data structure using an adjacency list.
*/
export class Graph {
adjacencyList = new Map();
/**
* Adds a vertex to the graph.
* @param {string} vertex - The vertex to add.
*/
addVertex(vertex) {
this.adjacencyList.set(vertex, []);
}
/**
* Adds an edge between two vertices.
* @param {string} vertex1 - The first vertex.
* @param {string} vertex2 - The second vertex.
*/
addEdge(vertex1, vertex2) {
this.adjacencyList.get(vertex1)?.push(vertex2);
this.adjacencyList.get(vertex2)?.push(vertex1); // For undirected graph
}
/**
* Performs a breadth-first search (BFS) starting from a given vertex.
* @param {string} start - The starting vertex.
* @returns {string[]} The vertices visited in BFS order.
*/
bfs(start) {
const visited = new Set();
const queue = [start];
const result = [];
while (queue.length > 0) {
const vertex = queue.shift();
if (!visited.has(vertex)) {
visited.add(vertex);
result.push(vertex);
queue.push(...this.adjacencyList.get(vertex));
}
}
return result;
}
}