Skip to content

Instantly share code, notes, and snippets.

@MiguelSavignano
Last active February 19, 2019 22:54
Show Gist options
  • Save MiguelSavignano/4a62d32510b7f1e952042174b094b0a1 to your computer and use it in GitHub Desktop.
Save MiguelSavignano/4a62d32510b7f1e952042174b094b0a1 to your computer and use it in GitHub Desktop.
Calculate work days. filter holidates and weekend.
const Holidays = require('date-holidays');
import * as moment from 'moment';
const holidays = new Holidays(process.env.LOCALE || 'ES');
// https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/getDay
const weekendDays = [6, 0];
const isWeekEnd = (date: Date) => weekendDays.indexOf(date.getDay()) !== -1;
const filterAviableDates = (dates: Array<Date>) => {
return dates.filter(date => {
if (holidays.isHoliday(date)) {
return false;
}
if (isWeekEnd(date)) {
return false;
}
return true;
});
};
const calculateAviableDates = (minimumDates: number) => (
dates: Array<Date>,
lastDateInit = null,
) => {
let lastDate = lastDateInit || dates.slice(-1)[0];
const datesFiltered = filterAviableDates(dates);
if (datesFiltered.length === minimumDates) {
return datesFiltered;
} else {
lastDate = moment(lastDate)
.add(1, 'day')
.toDate();
return calculateAviableDates(minimumDates)(
[...datesFiltered, lastDate],
lastDate,
);
}
};
console.log(calculateAviableDates(3)([new Date('2019-02-22')]));
// [ 2019-02-22T00:00:00.000Z, 2019-02-25T00:00:00.000Z, 2019-02-26T00:00:00.000Z ]
// simple implementation
const calculateAviableDates = (minimumDates: number) => (date: Date) => {
const allYearDays = _.times(100).map(index =>
moment(date)
.add(index, 'day')
.toDate(),
);
return _.take(filterAviableDates(allYearDays), minimumDates);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment