How do I simplify this simple JS Code

I am trying to get a value stored in variable (M100,50) … The following code works -

var A=100
var B=20
var C=30
var D=40
var E1= “M”
var E2= A;
var E3= B+C;
var E= E1+E2+“,”+E3;

But I want a more simplified way as in no E1 , E2 , E3 . I tried this E=“M”+A+“,”+B+C but its giving me the result as M100,2030 instead of M100,50

Hi there ManishBJain,

try it like this…

   var A=100;
   var B=20;
   var C=30;
   var D=40;
   var E='M'+A+','+(B+C);

coothead

1 Like

Thanks Mate.Oops I missed those brackets. It works now.

 
 
 
            No problem, you’re very welcome. :winky:
 
 
coothead

Can you help me with refining this code further - like if theres an easier and a good way of writing the same code, probably using Jquery or stuff.

<html>
<head>
    <script type="text/javascript"></script>
    </head>
    <body>
        <svg xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink">

    <path id="shape1" fill="" d=""/>    
</svg>

<script>
  
  var A=100;
  var B=20;
  var C=30;
  var D=40;

  var P1= "M"+A+","+(B+C);
  var P2="l"+A+","+0;
  var P3="l"+0+","+(A+A);
    
  var path = document.getElementById('shape1');
  var pathroute = P1+" "+P2+" "+P3+" "+"z";
  path.setAttribute('d', pathroute);
  path.setAttribute('fill','green')
    </script>
    </body>
</html>

No, stuff like jQuery won’t help, but other things like extracting out some functions will help to get some structure in there.

First, by using a drawShape() function, to help make it easier to understand what is happening:

function drawShape(container, pathroute, fillColor) {
    var path = document.getElementById(container);
    path.setAttribute("d", pathroute);
    path.setAttribute("fill", fillColor);
}

And second, by using moveTo() and lineTo() functions:

function moveTo(x, y) {
    return "M" + x + "," + y;
}
function lineTo(x, y) {
    return "l" + x + "," + y;
}
var route = [
    moveTo(a, b + c),
    lineTo(a, 0),
    lineTo(0, a + a)
];

And lastly, join them together for the pathroute:

var pathroute = route.join() + "z";
drawShape("shape1", pathroute, "green");

That way, the route can be easily modified and adjusted to fit different needs.

The resulting improved code looks like this:

function moveTo(x, y) {
    return "M" + x + "," + y;
}
function lineTo(x, y) {
    return "l" + x + "," + y;
}
function drawShape(container, pathroute, fillColor) {
    var path = document.getElementById(container);
    path.setAttribute("d", pathroute);
    path.setAttribute("fill", fillColor);
}

var a = 100;
var b = 20;
var c = 30;

var route = [
    moveTo(a, b + c),
    lineTo(a, 0),
    lineTo(0, a + a)
];

var pathroute = route.join() + "z";
drawShape("shape1", pathroute, "green");
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.