我有一个函数,用来尝试确定一组日期段是否符合标准。
我使用日期fns的distanceInDays
函数返回上一个分段的结束日期和当前分段的开始日期之间的距离的整数值。
(current.startDate - previous.endDate)
问题是reduce
函数给了我类型错误。
type DateSegment = {startDate: string, endDate: string} // ISO 8601 timestamps
const isValid = (current: ResidentialAddress, history: Array<ResidentialAddress>): boolean => {
if (!current || history.length === 0) return false;
const currentDate = formatInTimeZone(new Date(), 'UTC', 'yyyy-MM-dd');
// Convert current residence and residential history to segments.
const segments: DateSegment[] = [
{ startDate: current.startDate, endDate: currentDate },
...history.map(x => ({ startDate: x.startDate, endDate: x.endDate }))
];
// Sort them
const sorted = segments.sort((a, b) => isSameOrBefore(a.startDate, b.startDate));
const result = sorted.reduce((previousValue, currentValue) =>
differenceInDays(new Date(currentValue.startDate), new Date(previousValue.endDate))),
{endDate: currentDate}
);
console.log(result);
return true;
};
注意:当前住所没有结束日期,因此会向其提供当前日期。
这将返回间隔之间的距离数组。
const distances = array.map((item, index: number) => {
if (!array[index-1]) return
return item.start - array[index-1].end
}
)