Skip to content

Instantly share code, notes, and snippets.

@tjFogarty
Last active October 3, 2020 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjFogarty/e6cab497b457286c3fc2e76bfa43a889 to your computer and use it in GitHub Desktop.
Save tjFogarty/e6cab497b457286c3fc2e76bfa43a889 to your computer and use it in GitHub Desktop.
// given a date range
// and some unavailable dates
// construct multiple allocations to fit around them
// e.g., 21st - 28th with 23rd & 24th unavailable
// gives us 2 allocations: 21st - 22nd and 25th - 28th
import moment from 'moment';
function getDatesInRange(startDate, endDate) {
const dates = [];
let start = moment(startDate).clone();
while (start.isSameOrBefore(endDate, "day")) {
dates.push(start.format("YYYY-MM-DD"));
start = start.add(1, "day");
}
return dates;
}
const startDate = moment('2020-01-01');
const endDate = moment('2020-01-14');
const unavailableDates = ['2020-01-08', '2020-01-11', '2020-01-01', '2020-01-09'];
const originalDates = getDatesInRange(startDate, endDate);
const availableDates = originalDates.filter(oD => !unavailableDates.includes(oD));
// https://stackoverflow.com/a/51420305
const groupedDateRanges = availableDates.reduce((acc, date) => {
const group = acc[acc.length - 1];
if (moment(date).diff(moment(group[group.length - 1] || date), 'days') > 1) {
acc.push([date])
} else {
group.push(date);
}
return acc;
}, [[]]);
const allocationDates = groupedDateRanges.map((range) => {
return {
start: range[0],
end: range[range.length - 1],
days: moment(range[range.length - 1]).diff(range[0], 'd') + 1
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment