Developing the addEdge function for a two-way graph

Here are the requirements:

To demonstrate your understanding of the Graphs data structure, you need to complete the addEdge() method to establish bidirectional edges between two vertices.

Make sure to validate that each argument is an instance of the Vertex class.

An example Graph object named friendNetwork is provided for testing the functionality of the addEdge() method as you implement it.

This is my code snippet:

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;

I encountered an error message:

/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

I attempted to troubleshoot the add edge method hoping for a successful outcome. I even tried changing the class to Vertex instead of Graph, but unfortunately, my solution was not accepted.

Answer №1

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

class SocialGraph {
  constructor() {
    this.users = [];
  }

  addUser(name) {
    const newUser = new Vertex(name);
    this.users.push(newUser);
    return newUser;
  }

  addFriend(userOne, userTwo) {
    if (!(userOne instanceof Vertex) || !(userTwo instanceof Vertex)) {
      throw new Error('Both arguments must be instances of the Vertex class');
    }

    userOne.addEdge(userTwo);
    userTwo.addEdge(userOne);
  }

  displayUsers() {
    this.users.forEach(user => user.print());
  }
}

const mySocialNetwork = new SocialGraph();
const me = mySocialNetwork.addUser('Me');
const friend = mySocialNetwork.addUser('Friend');
mySocialNetwork.addFriend(me, friend);
mySocialNetwork.displayUsers();

module.exports = SocialGraph;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to access request or response objects in express.Js from any location?

Within an express.Js application, I aim to create a controller class responsible for managing the request and response for various other controllers. This includes tasks such as adding data to locals in the res object or deleting data from req.session. I ...

A bug encountered with AngularJS and dojox.charting: Error message 'nodeType' of null

My goal is to dynamically populate a div with various graphs from Dojo, depending on the current data model. However, I keep encountering the error message "Cannot read property 'nodeType' of null" when running my code. I suspect that this issu ...

List of Map Pins on Google Maps

I am looking to integrate PHP and Javascript to display multiple markers (at least 50) on a Google map. After reviewing the documentation at: https://developers.google.com/maps/documentation/javascript/examples/map-latlng-literal I noticed on line 15 it m ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

The OrhographicCamera is having difficulties capturing the entire scene in its render

Recently, I have been working on rendering a scene using three.js and WebGL in an isomorphic manner. In my research, I came across suggestions to use the OrthographicCamera for this purpose. However, upon implementing it, I noticed some strange outcomes. A ...

Transmit HTML message using the "textarea" tag through email

Whenever I try to send the content of my "textarea" via email, it always ends up being sent as a blank message. How can I fix this issue? Below is my PHP code: <?php $input = json_decode(file_get_contents("php://input"), true); $ToEmail = "<a href ...

Two separate occurrences hold identical values

I'm encountering an issue where instantiating a class two times results in the second instance retaining parameters from the first instance. Here's a simple example: var Test = function() {}; Test.prototype = { bonjour: null, hello: { h ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

The Bootstrap 4 Accordion feature ensures a smooth scrolling experience without jumping to the

Are you in need of assistance? If so, I have developed a Javascript code that enables an accordion card to scroll to the top when clicked on to expand. Provided below is an example of a Bootstrap 4 accordion along with the associated Javascript snippet: ...

The utilization of useEffect causes the page to go blank

Essentially, the issue is that once I include useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost.com/ping'); console.log(result) }; fetchData(); }, []); in my compone ...

What is causing the script blocks to exponentially increase in size within the VS2010 Debugger while executing an ASP.Net page with partial postbacks?

When working on an ASP.Net page that utilizes an UpdatePanel with validated controls for partial postbacks, an issue arises with the Visual Studio 2010 script debugger window. The debugger window starts displaying a continuous list of "Script Block" entrie ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Converting a JavaScript object into HTML output

I have received the following JSON data: [    {       "fields": {          "url": "http://www.domain_name.co.uk/MP3/SF560783-01-01-01.mp3\n",          "track_name": "Lion City ",          "release_id": 560783,    ...

Eliminating the nested API call within a loop

After making an API call to retrieve a set of data such as a list of users, I noticed that I am implementing a for loop and within it, I am making another API call to obtain each user's profile details based on their ID. I understand that this approac ...

Initializing data in VueJS for objects that do not already exist

I'm currently using Ajax to populate data properties for multiple objects, but the properties I want to bind to don't exist at the time of binding. For example: <template> <my-list v-bind:dataid="myobject ? myobject.data_id : 0">& ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

Steps for creating a personalized query or route in feathersjs

I'm feeling a bit lost and confused while trying to navigate through the documentation. This is my first time using feathersjs and I am slowly getting the hang of it. Let's say I can create a /messages route using a service generator to GET all ...

Having trouble with a peculiar for_of loop issue in Node.js: struggling to iterate correctly

Currently immersed in a Python project, I find myself in need of retrieving data from a Node.js API. Despite my limited knowledge of Node.js, I attempted to write some code for this purpose. Here is the code snippet: const SneaksAPI = require('sneaks ...

Tally up the values of selected checkboxes

  I'm in search of a method to tally up data-values associated with checkboxes. In the example provided below, selecting locations from the checkboxes results in the calculation of primary values, which are displayed in the green box. I also need to ...

Creating a Dynamic Bootstrap 4 Dropdown Menu using Jquery Hover

My Bootstrap Dropdown menu has a JQuery animation that is exactly what I want. However, when I move my cursor from the Dropdown's name (.dropdown) to an item in the dropdown, it starts acting erratically. $('.dropdown').hover(function() { ...