/
komarovdd
/
GraphViz
Обзор
Документация
Войти
/
komarovdd
/
GraphViz
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
scripts/graph.js
126 строк
3 KB
komarovdd
new project
09 фев 2026, 14:29
Верифицирован
09 фев 2026, 14:29
966388e
Код
Авторство
О чём код?
/** * Represents a single vertex in the graph. */ class Node { constructor(id, x = Math.random() * 800, y = Math.random() * 600) { this.id = id; this.x = x; this.y = y; this.vx = 0; this.vy = 0; this.fx = 0; // External force this.fy = 0; this.clusterId = null; this.isDragging = false; } } /** * Represents a weighted edge between two nodes. */ class Edge { constructor(source, target, weight) { this.source = source; this.target = target; this.weight = weight; } } /** * Manages the graph structure. */ class Graph { constructor() { this.nodes = new Map(); // Map<id, Node> this.edges = []; } addNode(id, x, y) { if (!this.nodes.has(id)) { this.nodes.set(id, new Node(id, x, y)); } return this.nodes.get(id); } addEdge(sourceId, targetId, weight) { // Ensure nodes exist this.addNode(sourceId); this.addNode(targetId); const edge = new Edge(sourceId, targetId, weight); this.edges.push(edge); return edge; } clear() { this.nodes.clear(); this.edges = []; } /** * Parses adjacency list format: "source target weight" * @param {string} text */ static parseAdjacencyList(text) { const graph = new Graph(); const lines = text.split('\n'); lines.forEach((line, index) => { line = line.trim(); if (!line || line.startsWith('#')) return; const parts = line.split(/\s+/); if (parts.length < 3) { console.warn(`Line ${index + 1} is invalid: "${line}"`); return; } const sourceId = parts[0]; const targetId = parts[1]; const weight = parseFloat(parts[2]); if (isNaN(weight)) { console.warn(`Invalid weight on line ${index + 1}: "${parts[2]}"`); return; } graph.addEdge(sourceId, targetId, weight); }); return graph; } /** * Exports graph to JSON compatible with the spec. */ toJSON() { return { nodes: Array.from(this.nodes.values()).map(n => ({ id: n.id, x: n.x, y: n.y })), edges: this.edges.map(e => ({ source: e.source, target: e.target, weight: e.weight })) }; } /** * Imports from JSON. */ static fromJSON(json) { const graph = new Graph(); json.nodes.forEach(n => { graph.addNode(n.id, n.x, n.y); }); json.edges.forEach(e => { graph.addEdge(e.source, e.target, e.weight); }); return graph; } } export { Node, Edge, Graph };