Function calculation of month

Asked

Viewed 43 times

0

I have a function that identifies the month through two entries, the initial month and also the difference that would be the maximum range of my array. At the same time there is another condition that in the case, limits my list to 6 values

var CountMes = 0;
function DataTabela(mesInicial, Diferenca) {
    var Meses = [];
    Meses.push(mesInicial);
    while (CountMes < 5 && Diferenca > CountMes) {
        CountMes++;
        mesInicial++;
        Meses.push(mesInicial);
    }
    alert(Meses.toString());
}

It works perfectly while we’re in the same year. My problem is, if my initial month entry is 11 (November) and my difference is 4, my list should have: November, December, January and February. However, as the account is on 12 basis and January would be equivalent to mesInicial = 1, how can I model my function to be adaptable to year transitions?

  • 1

    Have you ever thought about working with a array containing integers from 1 to 12 and restart the search on that array if the input and difference calculation exceeds 12?

  • Type, you find the position of the input in the array and then advance the boxes according to the difference, restarting the search in the array if it passes 12

1 answer

4


var CountMes = 0;
function DataTabela(mesInicial, Diferenca) {
    var Meses = [];
    Meses.push(mesInicial);
    while (CountMes < 5 && Diferenca > CountMes) {
        CountMes++;
        mesInicial++;
        //////
        if ( mesInicial > 12 ) mesInicial = 1;
        //////
        Meses.push(mesInicial);
    }
    alert(Meses.toString());
}


I could think of another more compact logic:

function DataTabela( mesInicial, Diferenca ) {
   var Meses = [];
   for ( i = 0; i < 5 && i < Diferenca; i++ ) {
      Meses.push( ( ( mesInicial + i - 1 ) % 12 ) + 1 );
   }
   alert(Meses.toString());
}

Note: the % is module operator (or "rest").

  • 1

    Yeah, that’s better than my suggestion.

  • 1

    @Erloncharles see the second part :)

  • Thanks for the moral :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.