首页 > 解决方案 > 如何引用已传递给 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(...)。所有帮助表示赞赏

标签: javascriptclassgraphvertex

解决方案


鉴于您的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);

推荐阅读