Able to delete vertices

This commit is contained in:
Ladd Hoffman 2023-07-09 23:48:45 -05:00
parent ea6e2d4494
commit 72c3bd1663
2 changed files with 36 additions and 16 deletions

View File

@ -142,6 +142,18 @@ export class Vertex {
cb: () => graph.resetEditorDocument(), cb: () => graph.resetEditorDocument(),
}); });
if (vertex) {
form.button({
id: 'delete',
name: 'Delete Vertex',
cb: () => {
graph.deleteVertex(vertex.id);
graph.redraw();
graph.resetEditorDocument();
},
});
}
return doc; return doc;
} }
} }

View File

@ -146,22 +146,6 @@ export class WeightedDirectedGraph {
return edges?.get(edgeKey); return edges?.get(edgeKey);
} }
deleteEdge(type, from, to) {
from = from instanceof Vertex ? from : this.getVertex(from);
to = to instanceof Vertex ? to : this.getVertex(to);
const edges = this.edgeTypes.get(type);
const edgeKey = Edge.getKey({ type, from, to });
if (!edges) return;
const edge = edges.get(edgeKey);
if (!edge) return;
to.edges.from.forEach((x, i) => (x === edge) && to.edges.from.splice(i, 1));
from.edges.to.forEach((x, i) => (x === edge) && from.edges.to.splice(i, 1));
edges.delete(edgeKey);
if (edges.size === 0) {
this.edgeTypes.delete(type);
}
}
getEdgeWeight(type, from, to) { getEdgeWeight(type, from, to) {
return this.getEdge(type, from, to)?.weight; return this.getEdge(type, from, to)?.weight;
} }
@ -219,4 +203,28 @@ export class WeightedDirectedGraph {
} }
return Array.from(this.vertices.values()).filter((vertex) => vertex.type === type).length; return Array.from(this.vertices.values()).filter((vertex) => vertex.type === type).length;
} }
deleteEdge(type, from, to) {
from = from instanceof Vertex ? from : this.getVertex(from);
to = to instanceof Vertex ? to : this.getVertex(to);
const edges = this.edgeTypes.get(type);
const edgeKey = Edge.getKey({ type, from, to });
if (!edges) return;
const edge = edges.get(edgeKey);
if (!edge) return;
to.edges.from.forEach((x, i) => (x === edge) && to.edges.from.splice(i, 1));
from.edges.to.forEach((x, i) => (x === edge) && from.edges.to.splice(i, 1));
edges.delete(edgeKey);
if (edges.size === 0) {
this.edgeTypes.delete(type);
}
}
deleteVertex(id) {
const vertex = this.getVertex(id);
for (const { type, from, to } of [...vertex.edges.to, ...vertex.edges.from]) {
this.deleteEdge(type, from, to);
}
this.vertices.delete(id);
}
} }