2
\$\begingroup\$

I'm using Node.js and Moment in order to retrieve the days until the next 8th:

const getDaysTillSalary = (day) => {
    const today = moment();
    const currentDay = moment().format('D');
    let currentMonth = moment().format('M');
    let currentYear = moment().format('Y');
    const isCurrentDayGreater = parseInt(currentDay) > day;

    currentYear = isCurrentDayGreater && parseInt(currentMonth) === 12 ? moment().add(1, 'year').format('Y') : currentYear;
    currentMonth = isCurrentDayGreater ? moment().add(1, 'months').format('M') : currentMonth;

    const salaryDate = moment(`${day}-${currentMonth}-${currentYear}`, 'DD-MM-YYYY');

    return salaryDate.diff(today, 'days');
}

getDaysTillSalary(8);

I'm sure there is a cleaner and maybe efficient way to solve this problem, and will be glad to get some feedback.

\$\endgroup\$
3
\$\begingroup\$
const currentDay = moment().format('D');

You use .format() a lot, instead use Moment.js's getters like .date(). This way you also don't have to use parseInt() since the getters return number's.


What about this solution:

const getDaysTillSalary = (day) => {
  let date = moment();
  let days = 0;
  while(date.date() !== 8) {
    date = date.add(1, 'day');
    days++;
  }
  return days;
}

It creates a variable and stores the current Moment.js date in it. Then it repeatedly adds one day using .add() and counts up until date.date() (the day of the month) returns 8. The days variable is then returned.

\$\endgroup\$
  • 1
    \$\begingroup\$ I downvoted your answer because you neither review the code nor explained what you did. \$\endgroup\$ – t3chb0t Dec 9 '17 at 19:28
  • \$\begingroup\$ @t3chb0t I'm new to the Code Review community. I added some feedback and explained my solution. \$\endgroup\$ – Niklas Higi Dec 9 '17 at 20:02
  • 1
    \$\begingroup\$ Well done. Now I can undo the vote ;-) \$\endgroup\$ – t3chb0t Dec 9 '17 at 20:08

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.