我如何引用 class 个实例作为键 JavaScript 传递到 Map 中

How can I reference class instances that I have passed into a Map as keys JavaScript

我正在实现一个图 class,使用 Map 作为邻接列表,使用一个简单的 class 顶点来表示图中的每个节点:

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");
    }
}

然后在我的图表中 class 我实现了一个构造函数和 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 实例变量。

我希望图形能够存储重复值,例如名称,因此使用 class 实例似乎是显而易见的选择,但现在我被困在如何访问它们包含的值上,因为我不确定如何在地图中搜索 class 个实例,即 graph.getAdjacencyList().get(...)。感谢所有帮助

鉴于您的 addVertex 方法创建了 Vertex 实例,并且 addEdge 方法需要该实例作为参数,您需要让这些方法的调用者可以使用它 -通过 returning 它:

…
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);