4
\$\begingroup\$

Will the below code work for adding Weekdays in all possible scenarios? eg, If I add 4 days to a "Thursday", the result should be next "Wednesday". Adding 1 day to a "Friday", "Saturday" or "Sunday" should be the next "Monday".

I am trying to get the nth working day (weekday) after a given day.

var addOneDay=function(date) {
    var result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    return result;
};

var addWeekDays = function(date,days) {
    var result = new Date(date.getTime());
    for (var i = 0; i < days; i++) {
        result = addOneDay(result);
        if (result.getDay()=== 6 || result.getDay()=== 0) i--;
    };
    return result;
};

var date = new Date(2016,1,18);
console.log(addWeekDays(date,4));
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to Code Review! Date-Time manipulation is usually tricky, so it is hard to say if it will work in every possible scenario, you should try to test it. That said, I'm sure we can help you improve your code! \$\endgroup\$ – Phrancis Feb 10 '16 at 18:25
  • \$\begingroup\$ It seems "all possible scenarios" could be covered with.... 7 tests? \$\endgroup\$ – Mathieu Guindon Feb 10 '16 at 18:50
  • 1
    \$\begingroup\$ @Mat'sMug To be thorough, 49 tests, maybe much more. \$\endgroup\$ – 200_success Feb 10 '16 at 18:53
  • \$\begingroup\$ @Mat'sMug Barring a calendar reform 7 tests might be "fine" \$\endgroup\$ – Phrancis Feb 10 '16 at 18:55
2
\$\begingroup\$

What is the expected behaviour if you add one weekday to a Saturday? Possible answers are: throw an exception, behavior is undefined, Monday, or Tuesday. Make a decision, and document it.

The use of var funcName = function(…) { … } is a bit unconventional compared to function funcName(…) { … }, but it's not wrong.

Other than that, I think that the code looks correct. For a more efficient way to add large intervals, you could add a number of integral weeks (7 * Math.floor(days / 5)) and advance the remainder (days % 5) the slow way.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.