Simplify an if/else statement?











up vote
6
down vote

favorite
2












I'm trying to simplify the following:



function handleDirection(src) {
if (src === 'left') {
if (inverse) {
tracker--;
} else {
tracker++;
}
} else {
if (inverse) {
tracker++;
} else {
tracker--;
}
}
}


to reduce the number of conditionals. The src will either be 'left' or 'right' always.










share|improve this question


















  • 1




    There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
    – James Thorpe
    4 hours ago






  • 3




    I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
    – Gabriele Petrioli
    4 hours ago






  • 3




    Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
    – Peter B
    4 hours ago








  • 1




    @PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
    – vlaz
    4 hours ago






  • 1




    I think the main benefit of this question is just to let others earn more reputation more easily!
    – lucumt
    3 hours ago

















up vote
6
down vote

favorite
2












I'm trying to simplify the following:



function handleDirection(src) {
if (src === 'left') {
if (inverse) {
tracker--;
} else {
tracker++;
}
} else {
if (inverse) {
tracker++;
} else {
tracker--;
}
}
}


to reduce the number of conditionals. The src will either be 'left' or 'right' always.










share|improve this question


















  • 1




    There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
    – James Thorpe
    4 hours ago






  • 3




    I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
    – Gabriele Petrioli
    4 hours ago






  • 3




    Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
    – Peter B
    4 hours ago








  • 1




    @PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
    – vlaz
    4 hours ago






  • 1




    I think the main benefit of this question is just to let others earn more reputation more easily!
    – lucumt
    3 hours ago















up vote
6
down vote

favorite
2









up vote
6
down vote

favorite
2






2





I'm trying to simplify the following:



function handleDirection(src) {
if (src === 'left') {
if (inverse) {
tracker--;
} else {
tracker++;
}
} else {
if (inverse) {
tracker++;
} else {
tracker--;
}
}
}


to reduce the number of conditionals. The src will either be 'left' or 'right' always.










share|improve this question













I'm trying to simplify the following:



function handleDirection(src) {
if (src === 'left') {
if (inverse) {
tracker--;
} else {
tracker++;
}
} else {
if (inverse) {
tracker++;
} else {
tracker--;
}
}
}


to reduce the number of conditionals. The src will either be 'left' or 'right' always.







javascript jquery if-statement conditional






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 4 hours ago









Rebecca O'Sullivan

324112




324112








  • 1




    There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
    – James Thorpe
    4 hours ago






  • 3




    I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
    – Gabriele Petrioli
    4 hours ago






  • 3




    Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
    – Peter B
    4 hours ago








  • 1




    @PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
    – vlaz
    4 hours ago






  • 1




    I think the main benefit of this question is just to let others earn more reputation more easily!
    – lucumt
    3 hours ago
















  • 1




    There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
    – James Thorpe
    4 hours ago






  • 3




    I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
    – Gabriele Petrioli
    4 hours ago






  • 3




    Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
    – Peter B
    4 hours ago








  • 1




    @PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
    – vlaz
    4 hours ago






  • 1




    I think the main benefit of this question is just to let others earn more reputation more easily!
    – lucumt
    3 hours ago










1




1




There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
– James Thorpe
4 hours ago




There's now a range of answers - one thing to bear in mind with this sort of thing is maintainability, that includes whether you yourself will understand what this code does next week. Make sure you pick a form of logic that is clear to you what it's doing at a glance - if that's the long form in your original question, stick with it.
– James Thorpe
4 hours ago




3




3




I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
– Gabriele Petrioli
4 hours ago




I'm voting to close this question as off-topic because it belongs to codereview.stackexchange.com
– Gabriele Petrioli
4 hours ago




3




3




Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
– Peter B
4 hours ago






Side note: your function uses 3 variables (src, inverse and tracker) but it has only 1 parameter (src) and no return value. For that reason it would not pass my code review, regardless of how you structure the ifs....
– Peter B
4 hours ago






1




1




@PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
– vlaz
4 hours ago




@PeterB I'd generally agree, but it's worth noting that context is key. If this were a method in an object, then it might be fine. This could be manipulating some sort of cursor (tracker) via commands ("left"/"right"), the object itself has a flag that it would be moved in the opposite direction (invert). However, as a free-floating function, that's indeed bad, as you're manipulating some not necessarily related global states.
– vlaz
4 hours ago




1




1




I think the main benefit of this question is just to let others earn more reputation more easily!
– lucumt
3 hours ago






I think the main benefit of this question is just to let others earn more reputation more easily!
– lucumt
3 hours ago














9 Answers
9






active

oldest

votes

















up vote
16
down vote



accepted










You could check with the result of the first check.



This is an exclusive OR check.



// typeof inverse === 'boolean'

function handleDirection(src) {
if (src === 'left' === inverse) {
tracker--;
} else {
tracker++;
}
}





share|improve this answer





















  • this is a good answer - was unaware you could chain conditions like this .. !!
    – treyBake
    4 hours ago










  • ^^ only in this special case
    – Nina Scholz
    4 hours ago










  • I see - is it only applicable to bool type vs condition is met?
    – treyBake
    4 hours ago










  • right, only if the last value is a boolean.
    – Nina Scholz
    4 hours ago






  • 1




    Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
    – treyBake
    4 hours ago


















up vote
8
down vote













function handleDirection(src)
{
if (inverse) {
(src === 'left' ? tracker-- : tracker++)
} else {
(src === 'left' ? tracker++ : tracker--)
}
}


both condition check inverse - might as well use that as your main focus and use src to dictate whether or not to -- or ++ using ternary operators.






share|improve this answer





















  • I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
    – Bob Brinks
    57 mins ago










  • @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
    – treyBake
    47 mins ago


















up vote
4
down vote













This could be simplified to a ternary expression which returns 1 or -1 depending on the state. Then you can just add that to the tracker.



function handleDirection(src) {
var delta = (src === 'left' && inverse) || (src !== 'left' && !inverse) ? -1 : 1;
tracker += delta;
}


This could then be simplified further using the logic which @NinaScholz pointed out in her answer:



function handleDirection(src) {
var delta = (src === 'left') === inverse ? -1 : 1;
tracker += delta;
}





share|improve this answer






























    up vote
    3
    down vote













    function handleDirection(src) {
    var i = 1;
    if(src === 'left')
    i = -1;

    if(inverse)
    tracker += i;
    else
    tracker -= i;
    }





    share|improve this answer

















    • 1




      This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
      – MagicLegend
      3 hours ago




















    up vote
    2
    down vote













    You can even do it with just one line of Code:



    function getDirectionOffset(src) {
    tracker += (src === 'left' ? 1 : -1) * (inverse ? -1 : 1);
    }





    share|improve this answer








    New contributor




    Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.

























      up vote
      1
      down vote













      Right now you are comparing on strings, which I wouldn't advise. If for example you use 'Left' instead of 'left' it will fail the first if statement. Perhaps a boolean could be of use here, since you can guarantee it only has two states.



      The if statements inside can be compressed via conditional operators.



      Perhaps something like this is what you are looking for:



      function handleDirection(src) {
      if (src) {
      inverse ? tracker-- : tracker++;
      } else {
      inverse ? tracker-- : tracker++;
      }
      }


      See: https://jsfiddle.net/9zr4f3nv/






      share|improve this answer




























        up vote
        1
        down vote













        You can use short circuiting syntax or ternary operators



        // by using short circuiting
        function handleDirection(src) {
        if (src == 'left') tracker = inverse && tracker-1 || tracker +1
        else tracker = inverse && tracker+1 || tracker -1
        }
        // by using ternary operator
        function handleDirection(src) {
        if (src == 'left') tracker = inverse ? tracker-1 : tracker +1
        else tracker = inverse ? tracker+1 : tracker -1
        }





        share|improve this answer




























          up vote
          1
          down vote













          Assuming inverse is a flag you'd set once, then you don't need to take it into account every time, you can calculate its impact once and just use it as it is, which will cut down your code branches and logic. If you want to change it as you go along, then you might need to separate the logic for the calculation, in order to re-use it.



          You can also then extract the movement direction into a self-contained function and your handleDirection becomes very simple - you calculate the direction you want to go based on src and the invert.






          let tracker = 0;

          //extract logic for the movement offset based on direction
          function getDirectionOffset(src) {
          return src === 'left' ? 1 : -1;
          }

          //have a setter for the invert property
          function setInverse(isInverse) {
          movementModifier = isInverse ? -1 : 1
          }

          //declare the variable dependent on the inverse property
          let movementModifier;

          //initialise movementModifier variable
          setInverse(false);

          function handleDirection(src) {
          const offset = getDirectionOffset(src) * movementModifier;

          tracker += offset;
          }


          // usage
          setInverse(true);

          handleDirection("left");
          handleDirection("left");
          handleDirection("right");

          console.log(tracker);





          With that said, all this suggests you shouldn't be using a function, or you should be using it differently. You can collect all that functionality in a class or instead have all the information passed around functions, so you don't have globals. Here is a sample object oriented implementation of the concept:






          class TrackerMover {
          constructor(inverse) {
          this.tracker = 0;
          this.movementModifier = inverse ? 1 : -1
          }

          handleDirection(src) {
          const offset = this.getDirectionOffset(src) * this.movementModifier;

          this.tracker += offset;
          }

          getDirectionOffset(src) {
          return src === 'left' ? -1 : 1;
          }

          getPosition() {
          return this.tracker;
          }
          }


          //usage
          const mover = new TrackerMover(true);

          mover.handleDirection("left");
          mover.handleDirection("left");
          mover.handleDirection("right");

          console.log(mover.getPosition())





          By the way, another alternative is to NOT compute the movement every time. You actually know what is happening every time - in effect, you have a truth table where your inputs are src === left and inverse and the outputs are how you modify your tracking.



          +--------+------------+--------+
          | isLeft | isInverted | Offset |
          +--------+------------+--------+
          | true | true | -1 |
          | true | false | 1 |
          | false | true | 1 |
          | false | false | -1 |
          +--------+------------+--------+


          So, you can just put that table in.






          let tracker = 0;
          let invert = false;

          const movementLookupTable = {
          "true": { },
          "false": { },
          }

          //it can be initialised as part of the above expression but this is more readable
          movementLookupTable[true ][true ] = -1;
          movementLookupTable[true ][false] = 1;
          movementLookupTable[false][true ] = 1;
          movementLookupTable[false][false] = -1;

          function handleDirection(src) {
          const offset = movementLookupTable[src === "left"][invert];

          tracker += offset;
          }


          // usage
          invert = true;

          handleDirection("left");
          handleDirection("left");
          handleDirection("right");

          console.log(tracker);





          In this case it might be an overkill but this approach might be useful if there are more flags (including more values for the flags) and/or end states. For example, maybe you want to introduce four directions, but you don't modify the tracker value if it's up or down.



          +-----------+------------+--------+
          | direction | isInverted | Offset |
          +-----------+------------+--------+
          | left | true | -1 |
          | left | false | 1 |
          | right | true | 1 |
          | right | false | -1 |
          | up | false | 0 |
          | up | true | 0 |
          | down | false | 0 |
          | down | true | 0 |
          +-----------+------------+--------+


          As you can see, now it's not just booleans, you can handle any value. Using a table, you also then change invert to be something like windDirection, so if the movement is left and the windDirection is right, the result is like what it is now, but you could have direction of left and wind going left, so you move further. Or you can move up and the wind direction is left so tracker (at this point the X coordinates) is going to actually be modified.



          +-----------+---------------+---------+
          | direction | windDirection | OffsetX |
          +-----------+---------------+---------+
          | left | right | -1 |
          | left | up | 1 |
          | left | down | 1 |
          | left | left | 2 |
          | right | up | -1 |
          | right | down | -1 |
          | right | right | -2 |
          | right | left | 1 |
          | up | up | 0 |
          | up | down | 0 |
          | up | left | 1 |
          | up | right | -1 |
          | down | up | 0 |
          | down | down | 0 |
          | down | left | 1 |
          | down | right | -1 |
          +-----------+---------------+---------+


          With four directions and four wind directions to take into account the logic can be quite annoying to both read and maintain in the future, while if you only have a lookup table, it's easy and you can easily extend this to even handle diagonals (let's assume they change the value by 0.5 instead of 1) and your algorithm would not really care as long as you just fetch the values from the table.






          share|improve this answer






























            up vote
            -1
            down vote













            Hope it helps.



            (src === 'left')?((inverse)?tracker--:tracker++):((tracker)?tracker++:tracker--)






            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53759675%2fsimplify-an-if-else-statement%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              9 Answers
              9






              active

              oldest

              votes








              9 Answers
              9






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              16
              down vote



              accepted










              You could check with the result of the first check.



              This is an exclusive OR check.



              // typeof inverse === 'boolean'

              function handleDirection(src) {
              if (src === 'left' === inverse) {
              tracker--;
              } else {
              tracker++;
              }
              }





              share|improve this answer





















              • this is a good answer - was unaware you could chain conditions like this .. !!
                – treyBake
                4 hours ago










              • ^^ only in this special case
                – Nina Scholz
                4 hours ago










              • I see - is it only applicable to bool type vs condition is met?
                – treyBake
                4 hours ago










              • right, only if the last value is a boolean.
                – Nina Scholz
                4 hours ago






              • 1




                Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
                – treyBake
                4 hours ago















              up vote
              16
              down vote



              accepted










              You could check with the result of the first check.



              This is an exclusive OR check.



              // typeof inverse === 'boolean'

              function handleDirection(src) {
              if (src === 'left' === inverse) {
              tracker--;
              } else {
              tracker++;
              }
              }





              share|improve this answer





















              • this is a good answer - was unaware you could chain conditions like this .. !!
                – treyBake
                4 hours ago










              • ^^ only in this special case
                – Nina Scholz
                4 hours ago










              • I see - is it only applicable to bool type vs condition is met?
                – treyBake
                4 hours ago










              • right, only if the last value is a boolean.
                – Nina Scholz
                4 hours ago






              • 1




                Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
                – treyBake
                4 hours ago













              up vote
              16
              down vote



              accepted







              up vote
              16
              down vote



              accepted






              You could check with the result of the first check.



              This is an exclusive OR check.



              // typeof inverse === 'boolean'

              function handleDirection(src) {
              if (src === 'left' === inverse) {
              tracker--;
              } else {
              tracker++;
              }
              }





              share|improve this answer












              You could check with the result of the first check.



              This is an exclusive OR check.



              // typeof inverse === 'boolean'

              function handleDirection(src) {
              if (src === 'left' === inverse) {
              tracker--;
              } else {
              tracker++;
              }
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 4 hours ago









              Nina Scholz

              172k1385149




              172k1385149












              • this is a good answer - was unaware you could chain conditions like this .. !!
                – treyBake
                4 hours ago










              • ^^ only in this special case
                – Nina Scholz
                4 hours ago










              • I see - is it only applicable to bool type vs condition is met?
                – treyBake
                4 hours ago










              • right, only if the last value is a boolean.
                – Nina Scholz
                4 hours ago






              • 1




                Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
                – treyBake
                4 hours ago


















              • this is a good answer - was unaware you could chain conditions like this .. !!
                – treyBake
                4 hours ago










              • ^^ only in this special case
                – Nina Scholz
                4 hours ago










              • I see - is it only applicable to bool type vs condition is met?
                – treyBake
                4 hours ago










              • right, only if the last value is a boolean.
                – Nina Scholz
                4 hours ago






              • 1




                Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
                – treyBake
                4 hours ago
















              this is a good answer - was unaware you could chain conditions like this .. !!
              – treyBake
              4 hours ago




              this is a good answer - was unaware you could chain conditions like this .. !!
              – treyBake
              4 hours ago












              ^^ only in this special case
              – Nina Scholz
              4 hours ago




              ^^ only in this special case
              – Nina Scholz
              4 hours ago












              I see - is it only applicable to bool type vs condition is met?
              – treyBake
              4 hours ago




              I see - is it only applicable to bool type vs condition is met?
              – treyBake
              4 hours ago












              right, only if the last value is a boolean.
              – Nina Scholz
              4 hours ago




              right, only if the last value is a boolean.
              – Nina Scholz
              4 hours ago




              1




              1




              Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
              – treyBake
              4 hours ago




              Ah, makes sense I suppose (bool) == (condition_met) .. +2 skill points to efficiency! thank you :)
              – treyBake
              4 hours ago












              up vote
              8
              down vote













              function handleDirection(src)
              {
              if (inverse) {
              (src === 'left' ? tracker-- : tracker++)
              } else {
              (src === 'left' ? tracker++ : tracker--)
              }
              }


              both condition check inverse - might as well use that as your main focus and use src to dictate whether or not to -- or ++ using ternary operators.






              share|improve this answer





















              • I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
                – Bob Brinks
                57 mins ago










              • @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
                – treyBake
                47 mins ago















              up vote
              8
              down vote













              function handleDirection(src)
              {
              if (inverse) {
              (src === 'left' ? tracker-- : tracker++)
              } else {
              (src === 'left' ? tracker++ : tracker--)
              }
              }


              both condition check inverse - might as well use that as your main focus and use src to dictate whether or not to -- or ++ using ternary operators.






              share|improve this answer





















              • I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
                – Bob Brinks
                57 mins ago










              • @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
                – treyBake
                47 mins ago













              up vote
              8
              down vote










              up vote
              8
              down vote









              function handleDirection(src)
              {
              if (inverse) {
              (src === 'left' ? tracker-- : tracker++)
              } else {
              (src === 'left' ? tracker++ : tracker--)
              }
              }


              both condition check inverse - might as well use that as your main focus and use src to dictate whether or not to -- or ++ using ternary operators.






              share|improve this answer












              function handleDirection(src)
              {
              if (inverse) {
              (src === 'left' ? tracker-- : tracker++)
              } else {
              (src === 'left' ? tracker++ : tracker--)
              }
              }


              both condition check inverse - might as well use that as your main focus and use src to dictate whether or not to -- or ++ using ternary operators.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 4 hours ago









              treyBake

              2,9693832




              2,9693832












              • I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
                – Bob Brinks
                57 mins ago










              • @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
                – treyBake
                47 mins ago


















              • I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
                – Bob Brinks
                57 mins ago










              • @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
                – treyBake
                47 mins ago
















              I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
              – Bob Brinks
              57 mins ago




              I downvote because both conditions check src alwell.. All you've done is flip the inner and outer conditions.
              – Bob Brinks
              57 mins ago












              @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
              – treyBake
              47 mins ago




              @BobBrinks a fair downvote! :) I think Nina's answer is spot on - was not aware you can chain conditions like that :)
              – treyBake
              47 mins ago










              up vote
              4
              down vote













              This could be simplified to a ternary expression which returns 1 or -1 depending on the state. Then you can just add that to the tracker.



              function handleDirection(src) {
              var delta = (src === 'left' && inverse) || (src !== 'left' && !inverse) ? -1 : 1;
              tracker += delta;
              }


              This could then be simplified further using the logic which @NinaScholz pointed out in her answer:



              function handleDirection(src) {
              var delta = (src === 'left') === inverse ? -1 : 1;
              tracker += delta;
              }





              share|improve this answer



























                up vote
                4
                down vote













                This could be simplified to a ternary expression which returns 1 or -1 depending on the state. Then you can just add that to the tracker.



                function handleDirection(src) {
                var delta = (src === 'left' && inverse) || (src !== 'left' && !inverse) ? -1 : 1;
                tracker += delta;
                }


                This could then be simplified further using the logic which @NinaScholz pointed out in her answer:



                function handleDirection(src) {
                var delta = (src === 'left') === inverse ? -1 : 1;
                tracker += delta;
                }





                share|improve this answer

























                  up vote
                  4
                  down vote










                  up vote
                  4
                  down vote









                  This could be simplified to a ternary expression which returns 1 or -1 depending on the state. Then you can just add that to the tracker.



                  function handleDirection(src) {
                  var delta = (src === 'left' && inverse) || (src !== 'left' && !inverse) ? -1 : 1;
                  tracker += delta;
                  }


                  This could then be simplified further using the logic which @NinaScholz pointed out in her answer:



                  function handleDirection(src) {
                  var delta = (src === 'left') === inverse ? -1 : 1;
                  tracker += delta;
                  }





                  share|improve this answer














                  This could be simplified to a ternary expression which returns 1 or -1 depending on the state. Then you can just add that to the tracker.



                  function handleDirection(src) {
                  var delta = (src === 'left' && inverse) || (src !== 'left' && !inverse) ? -1 : 1;
                  tracker += delta;
                  }


                  This could then be simplified further using the logic which @NinaScholz pointed out in her answer:



                  function handleDirection(src) {
                  var delta = (src === 'left') === inverse ? -1 : 1;
                  tracker += delta;
                  }






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 4 hours ago

























                  answered 4 hours ago









                  Rory McCrossan

                  240k29203244




                  240k29203244






















                      up vote
                      3
                      down vote













                      function handleDirection(src) {
                      var i = 1;
                      if(src === 'left')
                      i = -1;

                      if(inverse)
                      tracker += i;
                      else
                      tracker -= i;
                      }





                      share|improve this answer

















                      • 1




                        This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                        – MagicLegend
                        3 hours ago

















                      up vote
                      3
                      down vote













                      function handleDirection(src) {
                      var i = 1;
                      if(src === 'left')
                      i = -1;

                      if(inverse)
                      tracker += i;
                      else
                      tracker -= i;
                      }





                      share|improve this answer

















                      • 1




                        This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                        – MagicLegend
                        3 hours ago















                      up vote
                      3
                      down vote










                      up vote
                      3
                      down vote









                      function handleDirection(src) {
                      var i = 1;
                      if(src === 'left')
                      i = -1;

                      if(inverse)
                      tracker += i;
                      else
                      tracker -= i;
                      }





                      share|improve this answer












                      function handleDirection(src) {
                      var i = 1;
                      if(src === 'left')
                      i = -1;

                      if(inverse)
                      tracker += i;
                      else
                      tracker -= i;
                      }






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 4 hours ago









                      Alays

                      1148




                      1148








                      • 1




                        This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                        – MagicLegend
                        3 hours ago
















                      • 1




                        This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                        – MagicLegend
                        3 hours ago










                      1




                      1




                      This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                      – MagicLegend
                      3 hours ago






                      This creates an unnecessary extra variable imo... Using tracker-- and tracker++ is the correct way to increase and decrease the variable in this case. If it were desired to increase or lower the variable with more than one this might be a good guideline.
                      – MagicLegend
                      3 hours ago












                      up vote
                      2
                      down vote













                      You can even do it with just one line of Code:



                      function getDirectionOffset(src) {
                      tracker += (src === 'left' ? 1 : -1) * (inverse ? -1 : 1);
                      }





                      share|improve this answer








                      New contributor




                      Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                      Check out our Code of Conduct.






















                        up vote
                        2
                        down vote













                        You can even do it with just one line of Code:



                        function getDirectionOffset(src) {
                        tracker += (src === 'left' ? 1 : -1) * (inverse ? -1 : 1);
                        }





                        share|improve this answer








                        New contributor




                        Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.




















                          up vote
                          2
                          down vote










                          up vote
                          2
                          down vote









                          You can even do it with just one line of Code:



                          function getDirectionOffset(src) {
                          tracker += (src === 'left' ? 1 : -1) * (inverse ? -1 : 1);
                          }





                          share|improve this answer








                          New contributor




                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          You can even do it with just one line of Code:



                          function getDirectionOffset(src) {
                          tracker += (src === 'left' ? 1 : -1) * (inverse ? -1 : 1);
                          }






                          share|improve this answer








                          New contributor




                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          share|improve this answer



                          share|improve this answer






                          New contributor




                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.









                          answered 2 hours ago









                          Leuronics

                          211




                          211




                          New contributor




                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.





                          New contributor





                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          Leuronics is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






















                              up vote
                              1
                              down vote













                              Right now you are comparing on strings, which I wouldn't advise. If for example you use 'Left' instead of 'left' it will fail the first if statement. Perhaps a boolean could be of use here, since you can guarantee it only has two states.



                              The if statements inside can be compressed via conditional operators.



                              Perhaps something like this is what you are looking for:



                              function handleDirection(src) {
                              if (src) {
                              inverse ? tracker-- : tracker++;
                              } else {
                              inverse ? tracker-- : tracker++;
                              }
                              }


                              See: https://jsfiddle.net/9zr4f3nv/






                              share|improve this answer

























                                up vote
                                1
                                down vote













                                Right now you are comparing on strings, which I wouldn't advise. If for example you use 'Left' instead of 'left' it will fail the first if statement. Perhaps a boolean could be of use here, since you can guarantee it only has two states.



                                The if statements inside can be compressed via conditional operators.



                                Perhaps something like this is what you are looking for:



                                function handleDirection(src) {
                                if (src) {
                                inverse ? tracker-- : tracker++;
                                } else {
                                inverse ? tracker-- : tracker++;
                                }
                                }


                                See: https://jsfiddle.net/9zr4f3nv/






                                share|improve this answer























                                  up vote
                                  1
                                  down vote










                                  up vote
                                  1
                                  down vote









                                  Right now you are comparing on strings, which I wouldn't advise. If for example you use 'Left' instead of 'left' it will fail the first if statement. Perhaps a boolean could be of use here, since you can guarantee it only has two states.



                                  The if statements inside can be compressed via conditional operators.



                                  Perhaps something like this is what you are looking for:



                                  function handleDirection(src) {
                                  if (src) {
                                  inverse ? tracker-- : tracker++;
                                  } else {
                                  inverse ? tracker-- : tracker++;
                                  }
                                  }


                                  See: https://jsfiddle.net/9zr4f3nv/






                                  share|improve this answer












                                  Right now you are comparing on strings, which I wouldn't advise. If for example you use 'Left' instead of 'left' it will fail the first if statement. Perhaps a boolean could be of use here, since you can guarantee it only has two states.



                                  The if statements inside can be compressed via conditional operators.



                                  Perhaps something like this is what you are looking for:



                                  function handleDirection(src) {
                                  if (src) {
                                  inverse ? tracker-- : tracker++;
                                  } else {
                                  inverse ? tracker-- : tracker++;
                                  }
                                  }


                                  See: https://jsfiddle.net/9zr4f3nv/







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered 4 hours ago









                                  MagicLegend

                                  106112




                                  106112






















                                      up vote
                                      1
                                      down vote













                                      You can use short circuiting syntax or ternary operators



                                      // by using short circuiting
                                      function handleDirection(src) {
                                      if (src == 'left') tracker = inverse && tracker-1 || tracker +1
                                      else tracker = inverse && tracker+1 || tracker -1
                                      }
                                      // by using ternary operator
                                      function handleDirection(src) {
                                      if (src == 'left') tracker = inverse ? tracker-1 : tracker +1
                                      else tracker = inverse ? tracker+1 : tracker -1
                                      }





                                      share|improve this answer

























                                        up vote
                                        1
                                        down vote













                                        You can use short circuiting syntax or ternary operators



                                        // by using short circuiting
                                        function handleDirection(src) {
                                        if (src == 'left') tracker = inverse && tracker-1 || tracker +1
                                        else tracker = inverse && tracker+1 || tracker -1
                                        }
                                        // by using ternary operator
                                        function handleDirection(src) {
                                        if (src == 'left') tracker = inverse ? tracker-1 : tracker +1
                                        else tracker = inverse ? tracker+1 : tracker -1
                                        }





                                        share|improve this answer























                                          up vote
                                          1
                                          down vote










                                          up vote
                                          1
                                          down vote









                                          You can use short circuiting syntax or ternary operators



                                          // by using short circuiting
                                          function handleDirection(src) {
                                          if (src == 'left') tracker = inverse && tracker-1 || tracker +1
                                          else tracker = inverse && tracker+1 || tracker -1
                                          }
                                          // by using ternary operator
                                          function handleDirection(src) {
                                          if (src == 'left') tracker = inverse ? tracker-1 : tracker +1
                                          else tracker = inverse ? tracker+1 : tracker -1
                                          }





                                          share|improve this answer












                                          You can use short circuiting syntax or ternary operators



                                          // by using short circuiting
                                          function handleDirection(src) {
                                          if (src == 'left') tracker = inverse && tracker-1 || tracker +1
                                          else tracker = inverse && tracker+1 || tracker -1
                                          }
                                          // by using ternary operator
                                          function handleDirection(src) {
                                          if (src == 'left') tracker = inverse ? tracker-1 : tracker +1
                                          else tracker = inverse ? tracker+1 : tracker -1
                                          }






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered 4 hours ago









                                          Komal Bansal

                                          494




                                          494






















                                              up vote
                                              1
                                              down vote













                                              Assuming inverse is a flag you'd set once, then you don't need to take it into account every time, you can calculate its impact once and just use it as it is, which will cut down your code branches and logic. If you want to change it as you go along, then you might need to separate the logic for the calculation, in order to re-use it.



                                              You can also then extract the movement direction into a self-contained function and your handleDirection becomes very simple - you calculate the direction you want to go based on src and the invert.






                                              let tracker = 0;

                                              //extract logic for the movement offset based on direction
                                              function getDirectionOffset(src) {
                                              return src === 'left' ? 1 : -1;
                                              }

                                              //have a setter for the invert property
                                              function setInverse(isInverse) {
                                              movementModifier = isInverse ? -1 : 1
                                              }

                                              //declare the variable dependent on the inverse property
                                              let movementModifier;

                                              //initialise movementModifier variable
                                              setInverse(false);

                                              function handleDirection(src) {
                                              const offset = getDirectionOffset(src) * movementModifier;

                                              tracker += offset;
                                              }


                                              // usage
                                              setInverse(true);

                                              handleDirection("left");
                                              handleDirection("left");
                                              handleDirection("right");

                                              console.log(tracker);





                                              With that said, all this suggests you shouldn't be using a function, or you should be using it differently. You can collect all that functionality in a class or instead have all the information passed around functions, so you don't have globals. Here is a sample object oriented implementation of the concept:






                                              class TrackerMover {
                                              constructor(inverse) {
                                              this.tracker = 0;
                                              this.movementModifier = inverse ? 1 : -1
                                              }

                                              handleDirection(src) {
                                              const offset = this.getDirectionOffset(src) * this.movementModifier;

                                              this.tracker += offset;
                                              }

                                              getDirectionOffset(src) {
                                              return src === 'left' ? -1 : 1;
                                              }

                                              getPosition() {
                                              return this.tracker;
                                              }
                                              }


                                              //usage
                                              const mover = new TrackerMover(true);

                                              mover.handleDirection("left");
                                              mover.handleDirection("left");
                                              mover.handleDirection("right");

                                              console.log(mover.getPosition())





                                              By the way, another alternative is to NOT compute the movement every time. You actually know what is happening every time - in effect, you have a truth table where your inputs are src === left and inverse and the outputs are how you modify your tracking.



                                              +--------+------------+--------+
                                              | isLeft | isInverted | Offset |
                                              +--------+------------+--------+
                                              | true | true | -1 |
                                              | true | false | 1 |
                                              | false | true | 1 |
                                              | false | false | -1 |
                                              +--------+------------+--------+


                                              So, you can just put that table in.






                                              let tracker = 0;
                                              let invert = false;

                                              const movementLookupTable = {
                                              "true": { },
                                              "false": { },
                                              }

                                              //it can be initialised as part of the above expression but this is more readable
                                              movementLookupTable[true ][true ] = -1;
                                              movementLookupTable[true ][false] = 1;
                                              movementLookupTable[false][true ] = 1;
                                              movementLookupTable[false][false] = -1;

                                              function handleDirection(src) {
                                              const offset = movementLookupTable[src === "left"][invert];

                                              tracker += offset;
                                              }


                                              // usage
                                              invert = true;

                                              handleDirection("left");
                                              handleDirection("left");
                                              handleDirection("right");

                                              console.log(tracker);





                                              In this case it might be an overkill but this approach might be useful if there are more flags (including more values for the flags) and/or end states. For example, maybe you want to introduce four directions, but you don't modify the tracker value if it's up or down.



                                              +-----------+------------+--------+
                                              | direction | isInverted | Offset |
                                              +-----------+------------+--------+
                                              | left | true | -1 |
                                              | left | false | 1 |
                                              | right | true | 1 |
                                              | right | false | -1 |
                                              | up | false | 0 |
                                              | up | true | 0 |
                                              | down | false | 0 |
                                              | down | true | 0 |
                                              +-----------+------------+--------+


                                              As you can see, now it's not just booleans, you can handle any value. Using a table, you also then change invert to be something like windDirection, so if the movement is left and the windDirection is right, the result is like what it is now, but you could have direction of left and wind going left, so you move further. Or you can move up and the wind direction is left so tracker (at this point the X coordinates) is going to actually be modified.



                                              +-----------+---------------+---------+
                                              | direction | windDirection | OffsetX |
                                              +-----------+---------------+---------+
                                              | left | right | -1 |
                                              | left | up | 1 |
                                              | left | down | 1 |
                                              | left | left | 2 |
                                              | right | up | -1 |
                                              | right | down | -1 |
                                              | right | right | -2 |
                                              | right | left | 1 |
                                              | up | up | 0 |
                                              | up | down | 0 |
                                              | up | left | 1 |
                                              | up | right | -1 |
                                              | down | up | 0 |
                                              | down | down | 0 |
                                              | down | left | 1 |
                                              | down | right | -1 |
                                              +-----------+---------------+---------+


                                              With four directions and four wind directions to take into account the logic can be quite annoying to both read and maintain in the future, while if you only have a lookup table, it's easy and you can easily extend this to even handle diagonals (let's assume they change the value by 0.5 instead of 1) and your algorithm would not really care as long as you just fetch the values from the table.






                                              share|improve this answer



























                                                up vote
                                                1
                                                down vote













                                                Assuming inverse is a flag you'd set once, then you don't need to take it into account every time, you can calculate its impact once and just use it as it is, which will cut down your code branches and logic. If you want to change it as you go along, then you might need to separate the logic for the calculation, in order to re-use it.



                                                You can also then extract the movement direction into a self-contained function and your handleDirection becomes very simple - you calculate the direction you want to go based on src and the invert.






                                                let tracker = 0;

                                                //extract logic for the movement offset based on direction
                                                function getDirectionOffset(src) {
                                                return src === 'left' ? 1 : -1;
                                                }

                                                //have a setter for the invert property
                                                function setInverse(isInverse) {
                                                movementModifier = isInverse ? -1 : 1
                                                }

                                                //declare the variable dependent on the inverse property
                                                let movementModifier;

                                                //initialise movementModifier variable
                                                setInverse(false);

                                                function handleDirection(src) {
                                                const offset = getDirectionOffset(src) * movementModifier;

                                                tracker += offset;
                                                }


                                                // usage
                                                setInverse(true);

                                                handleDirection("left");
                                                handleDirection("left");
                                                handleDirection("right");

                                                console.log(tracker);





                                                With that said, all this suggests you shouldn't be using a function, or you should be using it differently. You can collect all that functionality in a class or instead have all the information passed around functions, so you don't have globals. Here is a sample object oriented implementation of the concept:






                                                class TrackerMover {
                                                constructor(inverse) {
                                                this.tracker = 0;
                                                this.movementModifier = inverse ? 1 : -1
                                                }

                                                handleDirection(src) {
                                                const offset = this.getDirectionOffset(src) * this.movementModifier;

                                                this.tracker += offset;
                                                }

                                                getDirectionOffset(src) {
                                                return src === 'left' ? -1 : 1;
                                                }

                                                getPosition() {
                                                return this.tracker;
                                                }
                                                }


                                                //usage
                                                const mover = new TrackerMover(true);

                                                mover.handleDirection("left");
                                                mover.handleDirection("left");
                                                mover.handleDirection("right");

                                                console.log(mover.getPosition())





                                                By the way, another alternative is to NOT compute the movement every time. You actually know what is happening every time - in effect, you have a truth table where your inputs are src === left and inverse and the outputs are how you modify your tracking.



                                                +--------+------------+--------+
                                                | isLeft | isInverted | Offset |
                                                +--------+------------+--------+
                                                | true | true | -1 |
                                                | true | false | 1 |
                                                | false | true | 1 |
                                                | false | false | -1 |
                                                +--------+------------+--------+


                                                So, you can just put that table in.






                                                let tracker = 0;
                                                let invert = false;

                                                const movementLookupTable = {
                                                "true": { },
                                                "false": { },
                                                }

                                                //it can be initialised as part of the above expression but this is more readable
                                                movementLookupTable[true ][true ] = -1;
                                                movementLookupTable[true ][false] = 1;
                                                movementLookupTable[false][true ] = 1;
                                                movementLookupTable[false][false] = -1;

                                                function handleDirection(src) {
                                                const offset = movementLookupTable[src === "left"][invert];

                                                tracker += offset;
                                                }


                                                // usage
                                                invert = true;

                                                handleDirection("left");
                                                handleDirection("left");
                                                handleDirection("right");

                                                console.log(tracker);





                                                In this case it might be an overkill but this approach might be useful if there are more flags (including more values for the flags) and/or end states. For example, maybe you want to introduce four directions, but you don't modify the tracker value if it's up or down.



                                                +-----------+------------+--------+
                                                | direction | isInverted | Offset |
                                                +-----------+------------+--------+
                                                | left | true | -1 |
                                                | left | false | 1 |
                                                | right | true | 1 |
                                                | right | false | -1 |
                                                | up | false | 0 |
                                                | up | true | 0 |
                                                | down | false | 0 |
                                                | down | true | 0 |
                                                +-----------+------------+--------+


                                                As you can see, now it's not just booleans, you can handle any value. Using a table, you also then change invert to be something like windDirection, so if the movement is left and the windDirection is right, the result is like what it is now, but you could have direction of left and wind going left, so you move further. Or you can move up and the wind direction is left so tracker (at this point the X coordinates) is going to actually be modified.



                                                +-----------+---------------+---------+
                                                | direction | windDirection | OffsetX |
                                                +-----------+---------------+---------+
                                                | left | right | -1 |
                                                | left | up | 1 |
                                                | left | down | 1 |
                                                | left | left | 2 |
                                                | right | up | -1 |
                                                | right | down | -1 |
                                                | right | right | -2 |
                                                | right | left | 1 |
                                                | up | up | 0 |
                                                | up | down | 0 |
                                                | up | left | 1 |
                                                | up | right | -1 |
                                                | down | up | 0 |
                                                | down | down | 0 |
                                                | down | left | 1 |
                                                | down | right | -1 |
                                                +-----------+---------------+---------+


                                                With four directions and four wind directions to take into account the logic can be quite annoying to both read and maintain in the future, while if you only have a lookup table, it's easy and you can easily extend this to even handle diagonals (let's assume they change the value by 0.5 instead of 1) and your algorithm would not really care as long as you just fetch the values from the table.






                                                share|improve this answer

























                                                  up vote
                                                  1
                                                  down vote










                                                  up vote
                                                  1
                                                  down vote









                                                  Assuming inverse is a flag you'd set once, then you don't need to take it into account every time, you can calculate its impact once and just use it as it is, which will cut down your code branches and logic. If you want to change it as you go along, then you might need to separate the logic for the calculation, in order to re-use it.



                                                  You can also then extract the movement direction into a self-contained function and your handleDirection becomes very simple - you calculate the direction you want to go based on src and the invert.






                                                  let tracker = 0;

                                                  //extract logic for the movement offset based on direction
                                                  function getDirectionOffset(src) {
                                                  return src === 'left' ? 1 : -1;
                                                  }

                                                  //have a setter for the invert property
                                                  function setInverse(isInverse) {
                                                  movementModifier = isInverse ? -1 : 1
                                                  }

                                                  //declare the variable dependent on the inverse property
                                                  let movementModifier;

                                                  //initialise movementModifier variable
                                                  setInverse(false);

                                                  function handleDirection(src) {
                                                  const offset = getDirectionOffset(src) * movementModifier;

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  setInverse(true);

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  With that said, all this suggests you shouldn't be using a function, or you should be using it differently. You can collect all that functionality in a class or instead have all the information passed around functions, so you don't have globals. Here is a sample object oriented implementation of the concept:






                                                  class TrackerMover {
                                                  constructor(inverse) {
                                                  this.tracker = 0;
                                                  this.movementModifier = inverse ? 1 : -1
                                                  }

                                                  handleDirection(src) {
                                                  const offset = this.getDirectionOffset(src) * this.movementModifier;

                                                  this.tracker += offset;
                                                  }

                                                  getDirectionOffset(src) {
                                                  return src === 'left' ? -1 : 1;
                                                  }

                                                  getPosition() {
                                                  return this.tracker;
                                                  }
                                                  }


                                                  //usage
                                                  const mover = new TrackerMover(true);

                                                  mover.handleDirection("left");
                                                  mover.handleDirection("left");
                                                  mover.handleDirection("right");

                                                  console.log(mover.getPosition())





                                                  By the way, another alternative is to NOT compute the movement every time. You actually know what is happening every time - in effect, you have a truth table where your inputs are src === left and inverse and the outputs are how you modify your tracking.



                                                  +--------+------------+--------+
                                                  | isLeft | isInverted | Offset |
                                                  +--------+------------+--------+
                                                  | true | true | -1 |
                                                  | true | false | 1 |
                                                  | false | true | 1 |
                                                  | false | false | -1 |
                                                  +--------+------------+--------+


                                                  So, you can just put that table in.






                                                  let tracker = 0;
                                                  let invert = false;

                                                  const movementLookupTable = {
                                                  "true": { },
                                                  "false": { },
                                                  }

                                                  //it can be initialised as part of the above expression but this is more readable
                                                  movementLookupTable[true ][true ] = -1;
                                                  movementLookupTable[true ][false] = 1;
                                                  movementLookupTable[false][true ] = 1;
                                                  movementLookupTable[false][false] = -1;

                                                  function handleDirection(src) {
                                                  const offset = movementLookupTable[src === "left"][invert];

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  invert = true;

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  In this case it might be an overkill but this approach might be useful if there are more flags (including more values for the flags) and/or end states. For example, maybe you want to introduce four directions, but you don't modify the tracker value if it's up or down.



                                                  +-----------+------------+--------+
                                                  | direction | isInverted | Offset |
                                                  +-----------+------------+--------+
                                                  | left | true | -1 |
                                                  | left | false | 1 |
                                                  | right | true | 1 |
                                                  | right | false | -1 |
                                                  | up | false | 0 |
                                                  | up | true | 0 |
                                                  | down | false | 0 |
                                                  | down | true | 0 |
                                                  +-----------+------------+--------+


                                                  As you can see, now it's not just booleans, you can handle any value. Using a table, you also then change invert to be something like windDirection, so if the movement is left and the windDirection is right, the result is like what it is now, but you could have direction of left and wind going left, so you move further. Or you can move up and the wind direction is left so tracker (at this point the X coordinates) is going to actually be modified.



                                                  +-----------+---------------+---------+
                                                  | direction | windDirection | OffsetX |
                                                  +-----------+---------------+---------+
                                                  | left | right | -1 |
                                                  | left | up | 1 |
                                                  | left | down | 1 |
                                                  | left | left | 2 |
                                                  | right | up | -1 |
                                                  | right | down | -1 |
                                                  | right | right | -2 |
                                                  | right | left | 1 |
                                                  | up | up | 0 |
                                                  | up | down | 0 |
                                                  | up | left | 1 |
                                                  | up | right | -1 |
                                                  | down | up | 0 |
                                                  | down | down | 0 |
                                                  | down | left | 1 |
                                                  | down | right | -1 |
                                                  +-----------+---------------+---------+


                                                  With four directions and four wind directions to take into account the logic can be quite annoying to both read and maintain in the future, while if you only have a lookup table, it's easy and you can easily extend this to even handle diagonals (let's assume they change the value by 0.5 instead of 1) and your algorithm would not really care as long as you just fetch the values from the table.






                                                  share|improve this answer














                                                  Assuming inverse is a flag you'd set once, then you don't need to take it into account every time, you can calculate its impact once and just use it as it is, which will cut down your code branches and logic. If you want to change it as you go along, then you might need to separate the logic for the calculation, in order to re-use it.



                                                  You can also then extract the movement direction into a self-contained function and your handleDirection becomes very simple - you calculate the direction you want to go based on src and the invert.






                                                  let tracker = 0;

                                                  //extract logic for the movement offset based on direction
                                                  function getDirectionOffset(src) {
                                                  return src === 'left' ? 1 : -1;
                                                  }

                                                  //have a setter for the invert property
                                                  function setInverse(isInverse) {
                                                  movementModifier = isInverse ? -1 : 1
                                                  }

                                                  //declare the variable dependent on the inverse property
                                                  let movementModifier;

                                                  //initialise movementModifier variable
                                                  setInverse(false);

                                                  function handleDirection(src) {
                                                  const offset = getDirectionOffset(src) * movementModifier;

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  setInverse(true);

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  With that said, all this suggests you shouldn't be using a function, or you should be using it differently. You can collect all that functionality in a class or instead have all the information passed around functions, so you don't have globals. Here is a sample object oriented implementation of the concept:






                                                  class TrackerMover {
                                                  constructor(inverse) {
                                                  this.tracker = 0;
                                                  this.movementModifier = inverse ? 1 : -1
                                                  }

                                                  handleDirection(src) {
                                                  const offset = this.getDirectionOffset(src) * this.movementModifier;

                                                  this.tracker += offset;
                                                  }

                                                  getDirectionOffset(src) {
                                                  return src === 'left' ? -1 : 1;
                                                  }

                                                  getPosition() {
                                                  return this.tracker;
                                                  }
                                                  }


                                                  //usage
                                                  const mover = new TrackerMover(true);

                                                  mover.handleDirection("left");
                                                  mover.handleDirection("left");
                                                  mover.handleDirection("right");

                                                  console.log(mover.getPosition())





                                                  By the way, another alternative is to NOT compute the movement every time. You actually know what is happening every time - in effect, you have a truth table where your inputs are src === left and inverse and the outputs are how you modify your tracking.



                                                  +--------+------------+--------+
                                                  | isLeft | isInverted | Offset |
                                                  +--------+------------+--------+
                                                  | true | true | -1 |
                                                  | true | false | 1 |
                                                  | false | true | 1 |
                                                  | false | false | -1 |
                                                  +--------+------------+--------+


                                                  So, you can just put that table in.






                                                  let tracker = 0;
                                                  let invert = false;

                                                  const movementLookupTable = {
                                                  "true": { },
                                                  "false": { },
                                                  }

                                                  //it can be initialised as part of the above expression but this is more readable
                                                  movementLookupTable[true ][true ] = -1;
                                                  movementLookupTable[true ][false] = 1;
                                                  movementLookupTable[false][true ] = 1;
                                                  movementLookupTable[false][false] = -1;

                                                  function handleDirection(src) {
                                                  const offset = movementLookupTable[src === "left"][invert];

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  invert = true;

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  In this case it might be an overkill but this approach might be useful if there are more flags (including more values for the flags) and/or end states. For example, maybe you want to introduce four directions, but you don't modify the tracker value if it's up or down.



                                                  +-----------+------------+--------+
                                                  | direction | isInverted | Offset |
                                                  +-----------+------------+--------+
                                                  | left | true | -1 |
                                                  | left | false | 1 |
                                                  | right | true | 1 |
                                                  | right | false | -1 |
                                                  | up | false | 0 |
                                                  | up | true | 0 |
                                                  | down | false | 0 |
                                                  | down | true | 0 |
                                                  +-----------+------------+--------+


                                                  As you can see, now it's not just booleans, you can handle any value. Using a table, you also then change invert to be something like windDirection, so if the movement is left and the windDirection is right, the result is like what it is now, but you could have direction of left and wind going left, so you move further. Or you can move up and the wind direction is left so tracker (at this point the X coordinates) is going to actually be modified.



                                                  +-----------+---------------+---------+
                                                  | direction | windDirection | OffsetX |
                                                  +-----------+---------------+---------+
                                                  | left | right | -1 |
                                                  | left | up | 1 |
                                                  | left | down | 1 |
                                                  | left | left | 2 |
                                                  | right | up | -1 |
                                                  | right | down | -1 |
                                                  | right | right | -2 |
                                                  | right | left | 1 |
                                                  | up | up | 0 |
                                                  | up | down | 0 |
                                                  | up | left | 1 |
                                                  | up | right | -1 |
                                                  | down | up | 0 |
                                                  | down | down | 0 |
                                                  | down | left | 1 |
                                                  | down | right | -1 |
                                                  +-----------+---------------+---------+


                                                  With four directions and four wind directions to take into account the logic can be quite annoying to both read and maintain in the future, while if you only have a lookup table, it's easy and you can easily extend this to even handle diagonals (let's assume they change the value by 0.5 instead of 1) and your algorithm would not really care as long as you just fetch the values from the table.






                                                  let tracker = 0;

                                                  //extract logic for the movement offset based on direction
                                                  function getDirectionOffset(src) {
                                                  return src === 'left' ? 1 : -1;
                                                  }

                                                  //have a setter for the invert property
                                                  function setInverse(isInverse) {
                                                  movementModifier = isInverse ? -1 : 1
                                                  }

                                                  //declare the variable dependent on the inverse property
                                                  let movementModifier;

                                                  //initialise movementModifier variable
                                                  setInverse(false);

                                                  function handleDirection(src) {
                                                  const offset = getDirectionOffset(src) * movementModifier;

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  setInverse(true);

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  let tracker = 0;

                                                  //extract logic for the movement offset based on direction
                                                  function getDirectionOffset(src) {
                                                  return src === 'left' ? 1 : -1;
                                                  }

                                                  //have a setter for the invert property
                                                  function setInverse(isInverse) {
                                                  movementModifier = isInverse ? -1 : 1
                                                  }

                                                  //declare the variable dependent on the inverse property
                                                  let movementModifier;

                                                  //initialise movementModifier variable
                                                  setInverse(false);

                                                  function handleDirection(src) {
                                                  const offset = getDirectionOffset(src) * movementModifier;

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  setInverse(true);

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  class TrackerMover {
                                                  constructor(inverse) {
                                                  this.tracker = 0;
                                                  this.movementModifier = inverse ? 1 : -1
                                                  }

                                                  handleDirection(src) {
                                                  const offset = this.getDirectionOffset(src) * this.movementModifier;

                                                  this.tracker += offset;
                                                  }

                                                  getDirectionOffset(src) {
                                                  return src === 'left' ? -1 : 1;
                                                  }

                                                  getPosition() {
                                                  return this.tracker;
                                                  }
                                                  }


                                                  //usage
                                                  const mover = new TrackerMover(true);

                                                  mover.handleDirection("left");
                                                  mover.handleDirection("left");
                                                  mover.handleDirection("right");

                                                  console.log(mover.getPosition())





                                                  class TrackerMover {
                                                  constructor(inverse) {
                                                  this.tracker = 0;
                                                  this.movementModifier = inverse ? 1 : -1
                                                  }

                                                  handleDirection(src) {
                                                  const offset = this.getDirectionOffset(src) * this.movementModifier;

                                                  this.tracker += offset;
                                                  }

                                                  getDirectionOffset(src) {
                                                  return src === 'left' ? -1 : 1;
                                                  }

                                                  getPosition() {
                                                  return this.tracker;
                                                  }
                                                  }


                                                  //usage
                                                  const mover = new TrackerMover(true);

                                                  mover.handleDirection("left");
                                                  mover.handleDirection("left");
                                                  mover.handleDirection("right");

                                                  console.log(mover.getPosition())





                                                  let tracker = 0;
                                                  let invert = false;

                                                  const movementLookupTable = {
                                                  "true": { },
                                                  "false": { },
                                                  }

                                                  //it can be initialised as part of the above expression but this is more readable
                                                  movementLookupTable[true ][true ] = -1;
                                                  movementLookupTable[true ][false] = 1;
                                                  movementLookupTable[false][true ] = 1;
                                                  movementLookupTable[false][false] = -1;

                                                  function handleDirection(src) {
                                                  const offset = movementLookupTable[src === "left"][invert];

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  invert = true;

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);





                                                  let tracker = 0;
                                                  let invert = false;

                                                  const movementLookupTable = {
                                                  "true": { },
                                                  "false": { },
                                                  }

                                                  //it can be initialised as part of the above expression but this is more readable
                                                  movementLookupTable[true ][true ] = -1;
                                                  movementLookupTable[true ][false] = 1;
                                                  movementLookupTable[false][true ] = 1;
                                                  movementLookupTable[false][false] = -1;

                                                  function handleDirection(src) {
                                                  const offset = movementLookupTable[src === "left"][invert];

                                                  tracker += offset;
                                                  }


                                                  // usage
                                                  invert = true;

                                                  handleDirection("left");
                                                  handleDirection("left");
                                                  handleDirection("right");

                                                  console.log(tracker);






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited 1 hour ago

























                                                  answered 3 hours ago









                                                  vlaz

                                                  4,00921930




                                                  4,00921930






















                                                      up vote
                                                      -1
                                                      down vote













                                                      Hope it helps.



                                                      (src === 'left')?((inverse)?tracker--:tracker++):((tracker)?tracker++:tracker--)






                                                      share|improve this answer

























                                                        up vote
                                                        -1
                                                        down vote













                                                        Hope it helps.



                                                        (src === 'left')?((inverse)?tracker--:tracker++):((tracker)?tracker++:tracker--)






                                                        share|improve this answer























                                                          up vote
                                                          -1
                                                          down vote










                                                          up vote
                                                          -1
                                                          down vote









                                                          Hope it helps.



                                                          (src === 'left')?((inverse)?tracker--:tracker++):((tracker)?tracker++:tracker--)






                                                          share|improve this answer












                                                          Hope it helps.



                                                          (src === 'left')?((inverse)?tracker--:tracker++):((tracker)?tracker++:tracker--)







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered 49 mins ago









                                                          G SURENDAR THINA

                                                          771615




                                                          771615






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.





                                                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                              Please pay close attention to the following guidance:


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53759675%2fsimplify-an-if-else-statement%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              What visual should I use to simply compare current year value vs last year in Power BI desktop

                                                              How to ignore python UserWarning in pytest?

                                                              Alexandru Averescu