Month calculation function

0

I have a function that identifies the month by means of 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 this 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 are 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. But since the account is base 12 and January would be equivalent to mesInicial = 1 , how can I model my function so that it is adaptable for year transitions?

    
asked by anonymous 13.03.2015 / 19:31

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:% is the module operator (or of "rest").

    
13.03.2015 / 19:37