lundi 20 février 2017

branching hell for coupon checking function javascript

So I am trying to do this kata. I know how to change the data into a format I can use, integers basically. But I don't know how to tackle the conditional branching, this is something I struggle with because of returning from the function with one value.

This is the input:

console.log(checkCoupon('123','123','September 5, 2014','October 1, 2014'))

I first start by matching the current and expiration date from the arguments with an index in the array, so I know if it is before exp date:

function checkCoupon(enteredCode, correctCode, currentDate, expirationDate){


var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

  var intDateCurrent = function(date, monthsArray){
    for (var i = 0; i < monthsArray.length; i++) {
      if (monthsArray[i].match(date)) return i;
  }
  return -1
  }

     var x = currentDate.slice(0,3)
  var y = expirationDate.slice(0,3)

  var currentMonthInt = intDateCurrent(x, months);
  var experationMonthInt = intDateCurrent(y, months);

Then I try to get a match on the day and year, with a regex and set some boolean settings. The match gives me an array with the day at [0] and year at [1] as strings:

  var currentDayAndYear =  currentDate.match(/\d+/g);

  var expDayAndYear =  expirationDate.match(/\d+/g);

  var yearsCleared = false;
  var  monthsCleared = false;
  var sameMonthButDaysAreCleared = false;

I then enter branching hell as I try and figure out how to use all these numbers I have to return true if the two first arguments equal one another and the current date is before the expiration date. I can't wade through conditional hell, its a nightmare. I get undefined. Not sure If I am in scope with currentMonthInt either.

  var checkTheYear = function(currentDate, expDate){
        if(Number(currentDate[1]) < Number(expDate[1])){
          return  yearsCleared = true;
           }
           if(currentMonthInt < experationMonthInt ){
             return  monthsCleared = true;
           }
         }

    checkTheYear(currentDayAndYear,  expDayAndYear)






    if(monthsCleared = false && (Number(currentDayAndYear[0]) < Number(expDayAndYear[0]))){
        return sameMonthButDaysAreCleared = true;
    }

    if(yearsCleared || sameMonthButDaysAreCleared){
      return true;
    }

I love big functions, but this is ridiculous. Please help!!

Aucun commentaire:

Enregistrer un commentaire