javascript - 如何引用已传递给 Map 的类实例作为键 JavaScript
问题描述
我正在使用 Map 作为邻接列表来实现一个图形类,并使用一个简单的 Vertex 类来表示图中的每个节点:
export class Vertex {
constructor(value) {
if (value) this.value = value;
else throw new Error("Value must be specified");
}
getValue() {
return this.value;
}
setValue(value) {
if (value) this.value = value;
else throw new Error("Value must be specified");
}
}
然后在我的图形类中,我实现了一个构造函数和 2 个添加顶点和边的方法:
export class UndirectedGraph {
constructor() {
this.adjacencyList = new Map();
}
addVertex(value) {
if (value) {
const vertex = new Vertex(value);
this.adjacencyList.set(vertex, []);
}
}
addEdge(to, from) {
if (
!to ||
!from ||
!(to.constructor === Vertex && from.constructor === Vertex)
) {
throw new Error("Arguments must be of type Vertex");
}
if (
!this.adjacencyList.get(to) ||
!this.adjacencyList.get(from)
) {
throw new Error(
"Both arguments must already be nodes in this undirected graph"
);
}
this.adjacencyList.get(to).push(from);
this.adjacencyList.get(from).push(to);
}
getAdjacencyList() {
return this.adjacencyList;
}
}
然后我想调用该addEdge()
函数在两个 Vertex 类型的实例之间创建一条边:
const graph = new UndirectedGraph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("B");
graph.addEdge(..., ...);
我应该将什么传递给addEdge()
函数以在“A”和“B”的特定实例之间创建边?我没有可以引用的 Vertex 实例的变量。
我希望图表能够存储重复值,例如名称,因此使用类实例似乎是显而易见的选择,但现在我被困在如何访问它们包含的值上,因为我不确定如何在地图即graph.getAdjacencyList().get(...)
。所有帮助表示赞赏
解决方案
鉴于您的addVertex
方法创建了Vertex
实例并且该addEdge
方法期望该实例作为参数,您需要使其对这些方法的调用者可用 - 通过return
ing 它:
…
addVertex(value) {
if (value) {
const vertex = new Vertex(value);
this.adjacencyList.set(vertex, []);
return vertex;
}
// else throw new Error("no value given")?
}
…
然后你可以像这样使用它
const graph = new UndirectedGraph();
const vertex1 = graph.addVertex("A");
const vertex2 = graph.addVertex("B");
const vertex3 = graph.addVertex("B");
graph.addEdge(vertex1, vertex2);
graph.addEdge(vertex1, vertex3);
graph.addEdge(vertex2, vertex3);
推荐阅读
- c# - 错误“指定的视觉对象已经是另一个视觉对象的子对象或 CompositionTarget 的根”
- java - 从坐标中获取城市名称
- java - 休眠:当延迟加载处于活动状态时,@PreUpdate 回调中的实体更改不会持续存在
- python - 通过 Scrapy (Python) 将抓取的数据导出到 csv 后,我在文件中得到了 †之类的字符
- docker - 服务重启后 Docker 节点关闭
- python - 是否可以将字符串作为代码传递给 html 页面?
- javascript - 试图将 promise-queue 示例转换为 nodejs
- vba - Excel 如果单元格 A 与另一张工作表上的单元格 A 匹配,则将文本添加到工作表 1 上的单元格 B
- c# - 从 C# 中的字符串列表中标记子字符串列表的算法
- python - arcGIS 中的 Python if/else 语句