简体   繁体   English

检测日期间隔之间差异的功能/ES6方法?

[英]Functional/ES6 way to detect differences between date intervals?

I have a function that I am using to try and determine if a set of date segments meets a criteria.我有一个 function 用于尝试确定一组日期段是否符合标准。

I am using date-fns' distanceInDays function to return an integer value of the distance between the previous segment's end date and the current segment's start date.我正在使用 date-fns 的distanceInDays function 返回上一个段的结束日期和当前段的开始日期之间的距离的 integer 值。

(current.startDate - previous.endDate)

Problem is that the reduce function is giving me type errors.问题是reduce function 给我类型错误。

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;
};

NB: The current residence does not have an end date, so the current date is provided to it.注意:当前住所没有结束日期,因此提供当前日期。

This will return an array of distances between intervals.这将返回间隔之间的距离数组。

const distances = array.map((item, index: number) => {
    if (!array[index-1]) return
    return item.start - array[index-1].end
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM