javascript. How to calculate the costs in each month?

I have object:

const obj = {
    "20": {budget:345, periodFrom:"2019-03-23", periodTo:"2019-04-17"},
    "39": {budget:234, periodFrom:"2019-03-11", periodTo:"2019-03-28"}
}

It is necessary to calculate how much was spent in each month, in this case in February and March. I wrote code that doesn't work ((.

const budgetSummary = {};


Object.values(obj).forEach(props => {
const { budget, periodFrom, periodTo } = props;

const daysInPeriods = moment(periodTo).diff(moment(periodFrom), 'days');
const costOneDay = budget / daysInPeriods;

let startDate = periodFrom;

while (startDate < periodTo) {
  const addingMonth = startDate.add(1, 'months');
  const formattedBudget = startDate.format('YYYY-MM');
  const days = startDate.clone().endOf('month').diff(startDate, 'days');
  const cost = budgetSummary[formattedBudget] || 0;

  budgetSummary[formattedBudget] = cost + days * costOneDay;

  startDate = addingMonth > periodTo ? periodTo : addingMonth;
}


});
console.log(budgetSummary);

But not what was expected is deduced. How to fix it? Oh, math, math ...

Upvotes: 1

Views: 509

Answers (1)

samura
samura

Reputation: 4395

With something like this at least your code runs:

const moment = require('moment');

const budgetSummary = {};
const obj = {
    "20": {budget:345, periodFrom:"2019-03-23", periodTo:"2019-04-17"},
    "39": {budget:234, periodFrom:"2019-03-11", periodTo:"2019-03-28"}
}

Object.values(obj).forEach(props => {
  const { budget, periodFrom, periodTo } = props;

  const daysInPeriods = moment(periodTo).diff(moment(periodFrom), 'days');
  const costOneDay = budget / daysInPeriods;

  let startDate = moment(periodFrom);

  while (startDate.diff(periodTo) < 0) {
    const addingMonth = startDate.add(1, 'months');
    const formattedBudget = startDate.format('YYYY-MM');
    const days = startDate.clone().endOf('month').diff(startDate, 'days');

    const cost = budgetSummary[formattedBudget] || 0;

    budgetSummary[formattedBudget] = cost + days * costOneDay;

    startDate = addingMonth > periodTo ? periodTo : addingMonth;
  }
});

console.log(budgetSummary);

I fixed missing requires and object initialization. Also fixed your startDate object which you were trying to .add but it was not a moment object.

Upvotes: 3

Related Questions