Home > Back-end >  how to generate a full array of data with range()
how to generate a full array of data with range()

Time:12-06

I've been trying to pre-populate an array of data using RxJS but I've hit a brick wall. In the end I've had to revert back to more traditional styles of coding.

You can see in the snippet below, I'm building an array of data and then returning it as stream with of (so that it can be combineLatest into a vm).

You can also see my failed attempt to use range() which is commented out below it.

This almost worked but the return value was a single BookingMonth rather than an array.

  public getMonthData(): Observable<BookingMonth[]> {
    const { seasonStart, seasonEnd } = getSeasonDates();

    let monthData: BookingMonth[] = [];
    for (
      let monthNum = seasonStart.getMonth();
      monthNum <= seasonEnd.getMonth();
      monthNum  
    ) {
      const currentMonthStartDate = new Date(2023, monthNum, 1);
      
      monthData.push({
        hasPrevious: seasonStart.getMonth() != monthNum,
        hasNext: seasonEnd.getMonth() != monthNum,
        startDate: currentMonthStartDate,
        endDate: getLastDayOfMonth(2023, monthNum),
        name: getMonthNameFull(currentMonthStartDate),
      });
    }

    return of(monthData);

    // const months$ = range(startDate.getMonth(), endDate.getMonth()).pipe(
    //   map(monthNum => {
    //     const currentMonthStartDate = new Date(2023, monthNum, 0);
    //     return {
    //       hasPrevious: startDate.getMonth() != monthNum,
    //       hasNext: endDate.getMonth() != monthNum,
    //       startDate: currentMonthStartDate,
    //       endDate: getLastDayOfMonth(2023, monthNum),
    //       name: getMonthNameFull(currentMonthStartDate)
    //     }
    //   })
    // );

    // return months$;
  }

Is there some way to use range() to generate the data and return the array? (Or a better way to stay inside RxJS more?)

Or am I trying to misuse this feature?

CodePudding user response:

You can use RxJS's toArray for the same effect.

return range(startDate.getMonth(), endDate.getMonth()).pipe(
  map(monthNum => ({
    monthNum, 
    currentMonthStartDate: new Date(2023, monthNum, 0)
  })),
  map(({monthNum, currentMonthStartDate}) => ({
    hasPrevious: startDate.getMonth() != monthNum,
    hasNext: endDate.getMonth() != monthNum,
    startDate: currentMonthStartDate,
    endDate: getLastDayOfMonth(2023, monthNum),
    name: getMonthNameFull(currentMonthStartDate),
  })),
  toArray()
);
  • Related