Skip to content

Instantly share code, notes, and snippets.

@zecar
Created April 21, 2021 06:58
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 zecar/a2f23fc6b574a7aac57fb0f35ecfe655 to your computer and use it in GitHub Desktop.
Save zecar/a2f23fc6b574a7aac57fb0f35ecfe655 to your computer and use it in GitHub Desktop.
Find next available date
// polyfill
if (!Array.prototype.some) {
Array.prototype.some = function(fun, thisArg) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.some called on null or undefined');
}
if (typeof fun !== 'function') {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(thisArg, t[i], i, t)) {
return true;
}
}
return false;
};
}
var freeDays = [ // [day, month]
[30, 4],
[3, 5],
[1, 6],
[21, 6],
[30, 11],
[1, 12]
]
function isFreeDay(today) {
var day = today.getDate()
var month = today.getMonth() + 1 // getMonth returns current month - 1
return freeDays.some(function(freeDay) {
return freeDay[0] == day && freeDay[1] == month
})
}
function findNextAvailableDate(today) {
today = today || new Date();
var dayNumber = today.getDay()
var hour = today.getHours()
// no shipment after 15:00
if (hour > 14) {
today.setDate(today.getDate() + 1)
// avoid infinite loop
today.setHours(1)
return findNextAvailableDate(today)
}
// no shipment during weekend
if (dayNumber === 0 || dayNumber === 6) {
if (dayNumber === 0) { // sunday
today.setDate(today.getDate() + 1)
} else { // saturday
today.setDate(today.getDate() + 1)
}
return findNextAvailableDate(today)
}
if (isFreeDay(today)) {
today.setDate(today.getDate() + 1)
return findNextAvailableDate(today)
}
return today
}
var shipmentDate = findNextAvailableDate()
var deliveryDate = new Date(shipmentDate)
deliveryDate.setDate(deliveryDate.getDate() + 1) // 24 hours delivery
deliveryDate = findNextAvailableDate(deliveryDate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment