You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现无向图addEdge方法遇Vertex类参数验证报错,请求排查

需求说明

基于图数据结构知识,完成addEdge()方法以实现两个顶点间的双向边;需验证每个参数均为Vertex类实例;提供friendNetwork实例用于测试方法行为。

我的代码

const Edge = require('./Edge.js');
const Vertex = require('./Vertex.js');

class Graph {
  constructor() {
    this.vertices = [];
  }

  addVertex(data) {
    const newVertex = new Vertex(data);
    this.vertices.push(newVertex);

    return newVertex;
  }

  addEdge(vertexOne, vertexTwo) {
    if (!(vertexOne instanceof Vertex) || !(vertexTwo instanceof Vertex)) {
      throw new Error('Edge start and end must both be Vertex');
    }
    
    const newEdge = new Edge(vertexOne, vertexTwo);
    vertexOne.addEdge(newEdge);
    vertexTwo.addEdge(newEdge);
  }

  print() {
    this.vertices.forEach(vertex => vertex.print());
  }
}

const friendNetwork = new Graph();
const friendSara = friendNetwork.addVertex('Sara');
const friendMeera = friendNetwork.addVertex('Meera');
friendNetwork.addEdge(friendSara, friendMeera);
friendNetwork.print();

module.exports = Graph;

报错信息

/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Vertex.js:13
      throw new Error('Edge start and end must both be Vertex');
      ^

Error: Edge start and end must both be Vertex
    at Vertex.addEdge (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Vertex.js:13:13)
    at Graph.addEdge (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Graph.js:22:15)
    at Object.<anonymous> (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Graph.js:34:15)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
    at internal/main/run_main_module.js:17:47

尝试过的操作

我编写上述代码后期望无报错运行,但持续触发上述错误;曾尝试修改Vertex类实现但被判定为错误答案,现寻求问题的解决方法。


内容的提问来源于stack exchange,提问作者jacksparrow987

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:45:22