Creating a new string by combining elements from an array using JavaScript

I need help creating a dot file from a string array.

edges =[["Source1" ,"interfaceA" , "high" , "Sink1" , "interfaceB" , "high"], 
        ["Source2" ,"interfaceC" , "high" , "Sink2" , "interfaceD" , "low"]]

This is how I want the data in my dot file to appear :

digraph mydot {
    "Source1" -> "Sink1"
    [
       label=<<font color="green">interfaceA</font>--&gt;<font color="green">interfaceB</font>>
    ];
    "Source2" -> "Sink2"
    [
       label=<<font color="green">interfaceC</font>--&gt;<font color="red">interfaceD</font>>
    ];
}

I have tried using the code below, but it's not giving me the expected output:

let mydot ='digraph mydot {  ';
     mydot += edges.map(edge => {
       let sourceInterfaceColor = "red";
       let sinkInterfaceColor = "red";
    if (edge[2]=="high")
      sourceInterfaceColor ="green";
    if(edge[5]=="high")
      sinkInterfaceColor ="green";

    mydot +=`\
                    ${edge[0]} -> ${edge[3]} \
        [                                    \
           label=<<font color= \"${sourceInterfaceColor}\">\"${edge[1]}\"</font>--&gt;<font color=\"${sinkInterfaceColor}\">${edge[4]}</font>> \
        ];`
        .stripMargin});
    mydot +='}';

How can I modify mydot to correctly generate the digraph data?

Answer №1

Here is a simple method to achieve the desired result you are looking for. Template literals, found here, provide support for multiline features.

const connections =[["Start" ,"pointA" , "high" , "End1" , "connectionB" , "high"], ["Start2" ,"pointC" , "high" , "End2" , "connectionD" , "low"]]

const connectionToString = conn => `
    "${conn[0]}" -> "${conn[3]}"
    [
       label=<<font color="green">${conn[1]}</font>--&gt;<font color="green">${conn[4]}</font>>
    ]
`.trimEnd()

const diagramToString = connections => `digraph mygraph {${connections.map(connectionToString).join('')}\n}`

console.log(diagramToString(connections))

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

JavaScript: What is the best way to increase the size of an array by adding new elements

I am attempting to generate an array containing the first 100 prime numbers. Here is the code I have written: var primeArray= []; var num= primeArray.length; function checkIfPrime(n) { if(n < 2) { return false; } for(i=2; i< ...

Completed processing graphical event layer

I am utilizing the Google Maps API v3 to build a map with multiple layers that are loaded upon user request. The layers are loaded in Geojson format using the following code: function getgeojson(json) { proplayer = new google.maps ...

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...

Unable to execute Protractor using Node.js command line

Hi there! Currently, I am in the process of setting up protractor for the very first time using Node.js. I found detailed instructions on how to do this on the AngularJS website under the section "Running E2E Tests": https://docs.angularjs.org/tutorial Ho ...

Moving the layout container towards the left: a quick guide

I am currently attempting to display the legend contents in a horizontal alignment within the layout container. The issue is that while the layout containing the legend aligns horizontally as desired, it extends beyond the screen border. I do not want the ...

Using Javascript's regular expressions to add double quotes around JSON values that are not already enclosed in quotes

Dealing with improperly formatted JSON values can be a challenge. The response I am working with is from a Java Servlet, specifically a hashmap, over which I have no control. Initially, it looked like this: { response={ type=000, products=[{id=1,name=prod ...

Retrieve an array containing a single item from a JSON using ObjectMapper

I'm currently working with a JSON object, ObjectMapper, and Realm in my project. The JSON structure looks like this: { "result": [ { "id": 20, "types": [ "now" ], "url": "/nl/whereto/ezrhgerigerg", "categor ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

Shadow effect on the dropdown body with accordion style

I've been developing an accordion control for my website that is nested inside a card. I have applied a box shadow to the header of the accordion which looks fine, but when it expands, the body pops up with a shadow as well. I'm trying to figure ...

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

Mixing various templates into a single outlet in ember.js

I have been working on an ember application that allows users to create, edit, and delete users, as well as view a list of all users. The app was created by following a tutorial on Ember (as I am still learning), but I am facing an issue. Currently, all th ...

Having issues with UTF8 encoding when utilizing AJAX to send the complete HTML source in JavaScript

I'm encountering difficulties when trying to send a complete page source using AJAX. Despite attempting to escape the content with escape(), encodeURI(), and encodeURIComponent(), I cannot successfully transmit utf8 characters. Below is my code snipp ...

How can you determine which of three intersecting three-dimensional objects should be displayed?

Let's imagine a scenario where multiple objects intersect at the same location. How can we specify which one to display in order to avoid constant flickering? http://jsfiddle.net/GYQ5v/187/ var scale = 1; var scene = new THREE.Scene(); var camera ...

Can you please explain the purpose of this code block and whether it is necessary for me to use in my project

I possess highly sensitive information that needs to be handled with care. Can you explain the purpose of this code snippet and its significance? app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.hea ...

Arranging and moving list elements without the use of jQuery UI (or any jQuery libraries at all?)

I have been searching for a JavaScript plugin that offers the same functionality as jQuery UI Sortable, which is the ability to drag and drop items to reorder them. In my case, these items are <li> tags. I prefer not to use jQuery UI because it is h ...

allocating a pointer to an array within a class

void UpdateStrings(char string1[], char string2[]){ str1= string1[]; str2= string2[]; } private: char str1[20]; char str2[20]; I need help identifying the issue in this code. Any insights would be appreciated! The error I am encounterin ...

Finding a specific value within a table: a step-by-step guide

To find the object, it could be located in any row or column, so a simple lookup won't suffice. Additionally, I want it to return the value of the cell to the right, but a formula that can provide its position would be ideal. Here is a Google Sheet ...

Find all the members belonging to a specific role in a Discord guild using discord.js client and store them in an array

I am attempting to create an array containing all users with a specific role, yet I keep encountering the following error message: TypeError: Cannot read property 'members' of undefined This is the code snippet that I am currently utilizing: var ...

What makes this CSS causing render blocking?

I've been meticulously following the Google PageSpeed guidelines in order to optimize the performance of my website. Upon running an analysis, Google provides me with a score based on their set guidelines. There's one particular guideline that ...

The Directive cannot be refreshed as a result of the ongoing "$digest already in progress" error

Within my controller, I have set a default value for a variable called "data". In my original project, I am using CouchCorner to retrieve data from a CouchDB and update the value of this variable. Inside a directive, I am watching the variable data and up ...