简体   繁体   中英

Generate a string from an array in Javascript

I am trying to generate a dot file based on the string array.

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

I want my output dot file data to look like:

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 tried the below code but returns something like digraph unnamed {,,}

        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 +='}';

What would be the right way to define mydot to get the correct digraph data.

Here is a straightforward way to achieve your desired output. Generally, template literals enable multiline features

 const edges =[["Source1","interfaceA", "high", "Sink1", "interfaceB", "high"], ["Source2","interfaceC", "high", "Sink2", "interfaceD", "low"]] const edgeToString = edge => ` "${edge[0]}" -> "${edge[3]}" [ label=<<font color="green">${edge[1]}</font>--&gt;<font color="green">${edge[4]}</font>> ] `.trimEnd() const digraphToString = edges => `digraph mydot {${edges.map(edgeToString).join('')}\n}` console.log(digraphToString(edges))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM