0

I have the following loop that checks if the date is holiday and thereon, fills up the Date[].

if (
          this._dateHelperService.isBusinessDay(temporalDate) &&
          !this._dateHelperService.isHoliday(temporalDate)
        ) {
          mNumberOfDays += 1;
          console.log(temporalDate.toDateString());
          console.log('entre')
          let tmpDate: Date[] = [...result.datesToPaint, temporalDate];
          result.datesToPaint = tmpDate;
          console.table(result.datesToPaint)
          // console.log(mNumberOfDays);
        }
        // re creating the date using a helper service
        if (mNumberOfDays !== numberOfDays) {
           temporalDate = 
           this._dateHelperService.addDays(temporalDate,1);
        }

        // helper service:
        addDays(date: Date, days: number): Date {
            date.setDate(date.getDate() + days);
            return date;
        }

The issue is that every time I assign a new element all the list data gets modified to the latest element. Here is a snapshot of the issue:

Sample output

I'm aware this may be related to the pointer I have on the global list I created at the start of the method for result.datesToPaint. I tried using the spread operator and assigning the date to another date temporally. Still not working. Thanks for the help!

Javiseeker
  • 47
  • 1
  • 11
  • Its hard to know what exactly is going wrong here since you did not provide your whole code. I am assuming you are modifying a Date somewhere? You should clone the date before modifying it when you use the same Date object in multiple places. – Tobias S. May 29 '22 at 18:36

1 Answers1

0

Thanks to @Tobias S. The solution was to adjust my addDays method to the following:

addDays(date: Date, days: number): Date {
    return new Date(date.setDate(date.getDate() + days));
  }

:) Be careful when populating date arrays!

Javiseeker
  • 47
  • 1
  • 11