2

How to add a conditional in the code below in case there are no dates in this range, it assigns a fixed value for costRate?


        function getPrices(allSeasons, checkin, checkout) {
            const day = 1000*60*60*24;
            return allSeasons.reduce( (totalPrice, season) => {
                let daysInSeason = Math.round(
                    (Math.min(+season.endDate+day, checkout) 
                    - Math.max(season.startDate, checkin)) / day);
                return totalPrice + (daysInSeason > 0 && daysInSeason * season.costRate);
            }, 0);
        } 

        const allSeasons = [
                {startDate: new Date(2017, 1-1, 1), endDate: new Date(2017, 4-1,30), costRate: 300},
                {startDate: new Date(2017, 5-1, 1), endDate: new Date(2017, 9-1,30), costRate: 400},
                {startDate: new Date(2017,10-1, 1), endDate: new Date(2017,12-1,31), costRate: 500}
            ],
            checkin = new Date(2017, 9-1,30),
            checkout = new Date(checkin.getTime() + (48 * 60 * 60 * 1000)),
            totalPrice = getPrices(allSeasons, checkin, checkout);

        console.log(totalPrice);



  • There are not always 24 hours in a day where daylight saving is observed, so `day = 1000*60*60*24` is not always correct, so you need to deal with that. [This answer](https://stackoverflow.com/a/11252167/257182) will help. – RobG May 03 '21 at 13:41

1 Answers1

3

I'm pretty sure you could replace daysInSeason * season.costRate, with daysInSeason * (season.costRate || VALUE). If season.costRate doesn't exist, it'll replace it with VALUE.

RobG raised a good point, and I think my answer is incorrect. You'd want to replace it with totalPrice + (daysInSeason>0? daysInSeason*season.costRate : fixedValue)

R3FL3CT
  • 551
  • 3
  • 14
  • The OP says "*in case there are no dates in this range*", which I think means if *daysInSeason* is zero, so it should be like `totalPrice + (daysInSeason>0? daysInSeason*season.costRate : fixedValue)`. The use of `>` guards against negative values and coerces values to Number. – RobG May 03 '21 at 13:49
  • RobG !! This solution works, but the problem is that if the date range is between a costRate and a fixed value, it does not calculate the average. – Leonardo Alexandre May 04 '21 at 18:43