( data: T[], startDate: ConfigType, endDate: ConfigType, unit: DateUnit, timezone?: string )
| 53 | * @param timezone - If not provided, timezone will not be processed, otherwise the output date will be converted to the corresponding timezone |
| 54 | */ |
| 55 | export function getDateArray<T extends { date: string }>( |
| 56 | data: T[], |
| 57 | startDate: ConfigType, |
| 58 | endDate: ConfigType, |
| 59 | unit: DateUnit, |
| 60 | timezone?: string |
| 61 | ): T[] { |
| 62 | if (data.length === 0) { |
| 63 | return []; |
| 64 | } |
| 65 | |
| 66 | const defaultItem: Omit<T, 'date'> = Object.keys(data[0]).reduce( |
| 67 | (acc: any, key) => { |
| 68 | if (key === 'date') { |
| 69 | return acc; |
| 70 | } |
| 71 | |
| 72 | acc[key] = 0; |
| 73 | |
| 74 | return acc; |
| 75 | }, |
| 76 | {} |
| 77 | ); |
| 78 | |
| 79 | const arr: T[] = []; |
| 80 | const { diff, add, normalize } = createDateUnitFn(unit, timezone); |
| 81 | const n = diff(endDate, startDate) + 1; |
| 82 | |
| 83 | const dataMap = new Map<number, T>(); |
| 84 | data.forEach((item) => { |
| 85 | const timestamp = timezone |
| 86 | ? normalize(dayjs.tz(item.date, timezone)).valueOf() |
| 87 | : normalize(dayjs(item.date)).valueOf(); |
| 88 | dataMap.set(timestamp, item); |
| 89 | }); |
| 90 | |
| 91 | for (let i = 0; i < n; i++) { |
| 92 | const t = normalize(add(startDate, i)); |
| 93 | const target = dataMap.get(t.valueOf()); |
| 94 | |
| 95 | arr.push({ ...defaultItem, ...target, date: formatDate(t, timezone) } as T); |
| 96 | } |
| 97 | |
| 98 | return arr; |
| 99 | } |
| 100 | |
| 101 | /** |
| 102 | * Infer the time range from the dates |
no test coverage detected