1
votes

I need to create a javascript function named as NextDay(). This function should print me the name of next day in the console.

I have created a function as below:

    //Function to Print the name of Next Day in Javascript
    var NextDay = (function () {
    counter = 0;
    var nextDay = function () {

        var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", 
                     "Friday", "Saturday"];
        var date = new Date();
        var dayNumber = date.getDay() + counter;
        if (dayNumber < 6) {
            dayNumber = dayNumber;
        }
        else {
            dayNumber = (dayNumber % 6);
        }
        var dayName = days[dayNumber];
        counter += 1;
        return dayName;
    };

    return nextDay;
})();
NextDay();
NextDay();
NextDay();
NextDay();
NextDay();
NextDay();
NextDay();
NextDay();

I am expecting an output as :

Saturday Sunday
Monday Tuesday Wednesday Thursday Friday Saturday

But I am getting an output as below: Sunday Monday Tuesday Wednesday Thursday Friday Sunday Monday

I believe I am missing something very small here because of which I am getting a day skipped here. Please suggest

2

2 Answers

1
votes

Im not shure which of your math is going wrong, but theres an easier way:

var counter =(new Date).getDay();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var nextDay = function () {
    var day=days[counter];
    counter = (counter+1)%7;
    return day;
};
1
votes

Generator function may be handy.

function* nextDay() {
  let i = 0,
      days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  while (i < 7) {
    yield console.log(days[i++]);
    if (i == 7) i = 0;
  }
}

let gen = nextDay();
gen.next();
gen.next();
gen.next();
gen.next();
gen.next();
gen.next();
gen.next();
gen.next();
gen.next();