问题
I want to find the last date that is contiguous with all the previous dates in a list.
Pictorially:
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
}
The ternary if statement at the end is supposed to ensure that if no dates are contiguous, then the first should be taken.
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.
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.
N.B. this does not pass tests, so it's not appropriate for codereview.stackexchange.com
回答1:
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.
Below is the modification I made
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;
}
来源:https://stackoverflow.com/questions/32725549/filter-out-non-contiguous-date-using-momentjs-and-twix-js