Skip to content

Instantly share code, notes, and snippets.

@pixelbacon
Last active May 24, 2021 08:44
Show Gist options
  • Save pixelbacon/cc4517f0b747507916f6 to your computer and use it in GitHub Desktop.
Save pixelbacon/cc4517f0b747507916f6 to your computer and use it in GitHub Desktop.
MomentJS iterate through daily start/end, check for clashes
var moment = require('moment'); // http://momentjs.com/docs/
var _ = require('lodash'); // https://lodash.com/docs
function(collectionsWithDateValues){
var slots = [];
var hours = {
start: 7, // 7am
end: 21, // 9pm
window: 2 // How long each item should be slotted for.
};
var rightNow = moment().add(0, 'days').hours(hours.start).minute(0).second(0);
var cutoff = moment(rightNow).add(14,'days'); // Check the next 2 weeks.
for( rightNow ; rightNow.isBefore(cutoff) ; rightNow.add(hours.window, 'hours') ){
// Check if we're going beyond the daily cutoff, go to the next day
if(rightNow.isAfter(moment(rightNow).hour(hours.end))){
rightNow.add(1, 'days').hour(hours.start);
}
var foundClash = false;
_.forEach(collectionsWithDateValues, function(item){
// Check if the item is within now and the slotted time
foundClash = moment(item.date).isBetween(rightNow, moment(rightNow).add(hours.window, 'hours').subtract(1, 'minutes').seconds(59));
});
if(!foundClash){
slots.push(rightNow.toString());
}
}
return slots;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment