Search code examples
javascriptdrydesign-principles

Apply DRY principle with JavaScript


I am currently stuck trying to apply the DRY principle in this scenario. Here is the code. As you can see, I am trying to run scripts containing different variables on different days. I mean, I could simply shoot out a bunch of else if statements until Friday, but that just does not seem like the right way to do things. Any pointers?

Thanks

<script>
    function timer(){
        window.alert("The timer will start in 1 minute. Get ready!");
        var dayVar = new Date().getDay();
           if(dayVar == 1){
             var monPhp = "<?php echo $homeMon2 ?>";
             var min = 60 * monPhp;
               setInterval(function(){
                 var a = new Date();
                 document.getElementById("result").innerHTML = "Minutes : " + min ;
                 min--;
                if(min == -1){
                  window.alert("Times up!");
                  min = 60 * monPhp;
                }           
               },60000); 
           } else if (dayVar == 2){
               var tuePhp = "<?php echo $homeTue2 ?>";
               var min = 60 * tuePhp;
               setInterval(function(){
                  var a = new Date();
                  document.getElementById("result").innerHTML = "Minutes : " + min ;
                  min--;
                  if(min == -1){
                      window.alert("Times up!");
                      min = 60 * tuePhp;
                  }
               },60000); 
            }
      }
</script>

Solution

  • In your PHP, create an array

    <?php
    
        $arr = Array($homeSun2, $homeMon2, $homeTue2, $homeWed2 ... etc);
    ?>
    

    Then use it

    function timer(){
        var days   = <?php echo json_encode($arr); ?>;
        var dayVar = new Date().getDay();
    
        window.alert("The timer will start in 1 minute. Get ready!");
    
        var min  = 60 * days[dayVar];
        var temp = min;
    
        setInterval(function(){
            var a = new Date();
            document.getElementById("result").innerHTML = "Minutes : " + (temp--) ;
            if(temp == -1){
                window.alert("Times up!");
                temp = min;
            }           
        },60000);
    }