Last active
February 19, 2019 22:54
-
-
Save MiguelSavignano/4a62d32510b7f1e952042174b094b0a1 to your computer and use it in GitHub Desktop.
Calculate work days. filter holidates and weekend.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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