rotaready / moment-range

Fancy date ranges for Moment.js
The Unlicense
1.69k stars 202 forks source link

Iterate over array of starts, ends #257

Closed chrismatchett closed 5 years ago

chrismatchett commented 5 years ago

Hi,

Can I use moment-range to iterate over an array of start, end datetimes and identify which, if any, overlap? Most examples when I search are for comparing two sets of datetimes but I can't get my head around how to test all items in an array.

Thanks,

Chris

carlholloway commented 5 years ago

This isn't super efficient, but it checks each range against every other range, and returns any that overlap. (I haven't tested this works but it should!)

const ranges = [
  moment.range(moment('2018-01-01'), moment('2018-02-01')),
  moment.range(moment('2018-01-14'), moment('2018-02-14')),
  moment.range(moment('2018-02-01'), moment('2018-03-01')),
];

const overlappingRanges = ranges.find((range, index) => {
  return ranges.some((candidate, candidateIndex) => {
    return index !== candidateIndex && candidate.overlaps(range);
  });
});
ALiangLiang commented 5 years ago

Hi @chrismatchett Maybe you can use moment-ranges#overlaps. 🙂