UNPKG

lgrthms

Version:

Algorithms and data structures for your JavaScript and TypeScript projects 🧑‍💻

88 lines (87 loc) 2.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Graph = void 0; class Node { constructor(id, value) { this.id = id; this.value = value; this.edges = {}; } } class Graph { constructor() { this.DEFAULT_WEIGHT = 1; this._nextId = 1; this._size = 0; this._graph = {}; } get size() { return this._size; } // O(1) time | O(1) space getNode(id) { return this._graph[id]; } // O(e) time | O(e) space — where e is the number of edges of the given node getEdges(id) { const node = this.getNode(id); if (!node) { return []; } return Object.keys(node.edges).map(neighborId => ({ neighborId, weight: node.edges[neighborId] })); } // O(1) time | O(1) space addNode(value, id) { if (id && !['number', 'string'].includes(typeof id)) { throw new Error('Cannot add node with given id, id must be a number or a string'); } else if (typeof id === 'number') { this._nextId = id + 1; } else if (!id) { id = this._nextId; this._nextId++; } id = typeof id === 'number' ? String(id) : id; const node = new Node(id, value); this._graph[id] = node; this._size++; return node; } // O(1) time | O(1) space addEdge(nodeId, neighborId, weight = this.DEFAULT_WEIGHT) { if (!this._graph[nodeId]) { throw new Error('Cannot find node with given nodeId'); } if (!this._graph[neighborId]) { throw new Error('Cannot find node with given neighborId'); } const node = this._graph[nodeId]; node.edges[neighborId] = weight; } // O(n) time | O(1) space removeNode(id) { if (!this._graph[id]) { return; } delete this._graph[id]; for (const nodeId in this._graph) { this.removeEdge(nodeId, id); } this._size--; } // O(1) time | O(1) space removeEdge(nodeId, neighborId) { if (!this._graph[nodeId]) { return; } const node = this._graph[nodeId]; delete node.edges[neighborId]; } // O(1) time | O(1) space adjacent(nodeId, neighborId) { const node = this.getNode(nodeId); return Boolean(node && neighborId in node.edges); } } exports.Graph = Graph;