使用momentjs和twix.js过滤掉不连续的日期 [英] Filter out non-contiguous date using momentjs and twix.js
问题描述
我想在列表中找到与所有先前日期相邻的最后日期。
I want to find the last date that is contiguous with all the previous dates in a list.
图为:
在上面的图片中,我想要带圆圈的日期。
In the above picture I want the circled 'date'.
我有一个公开功能的服务(从内存中复制,因为我目前不在工作中):
I have a service that exposes a function (copied from memory, as I am not currently at work):
var maxContiguousDates = function(listOfDates1, listOfDates2){
ranges = combineDatesIntoTwixRanges(listOfDates1, listOfDates2);
//Sort with earliest start first
sortedRanges = _.sortBy(ranges,function(range){return -range.start.unix()})
return moment.max(sortedRanges.filter(function(range,index){
var currentRange = range;
var previousRange = undefined;
if(index){
previousRange = sortedRanges[index-1];
}
return previousRange?previousRange.overlap(currentRange):true;
}).end) //I don't remember the specifics I think there is a mistake in this version of the code - the copy at work runs and works for contiguous dates
}
三元if语句位于
但是在我的测试中,我输入的是不连续日期的列表,它返回最后的总日期。
However in my test, where I enter a list of non-contiguous dates, it returns the last total date.
我想,除非我犯了一个小小的错误,否则此方法应该可以工作。
I feel like, except if I have made a minor small mistake, this method should work.
有更好的方法吗?我在momentjs或twix.js中没有看到巧妙的排序或连续性功能。我也看不到任何其他方式。
Is there a better approach? I didn't see a clever sort, or contiguousness function in momentjs or twix.js. Nor do I see any other way of doing this.
请告诉我您是否可以理解为什么这样做无法按预期进行,或者是否有更好的方法。
Please let me know if you can see why this would not work as intended, or if there is a better approach.
NB这不会通过测试,因此不适用于codereview.stackexchange.com
N.B. this does not pass tests, so it's not appropriate for codereview.stackexchange.com
推荐答案
问题是您尚未定义方式或从过滤器中获取日期。另外,当您获得不连续的日期范围时,过滤器也不会停止。
The problem is that you have not defined a way or getting dates out of the filter. Also, your filter won't stop when you get a non-contiguous date range.
以下是我所做的修改
var maxContiguousDate = function(listOfDates1, listOfDates2){
ranges = combineDatesIntoTwixRanges(listOfDates1, listOfDates2);
//Sort with earliest start first
sortedRanges = _.sortBy(ranges,function(range){return -range.start.unix()})
//combine all ranges if they overlap, or the previous range as a short circuit
contiguousRange = sortedRanges.reduce(function(previousRange,currentRange){
if(previousRange.overlaps(currentRange)){
return previousRange.union(currentRange);
}else{
return previousRange;
})
return contiguousRange.end;
}
这篇关于使用momentjs和twix.js过滤掉不连续的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!