From acbac64ed0a39b1c5dc2340c30e6a46819a16ff3 Mon Sep 17 00:00:00 2001 From: "Antonio Eduardo (SkyaTura)" Date: Mon, 6 Jun 2022 14:18:38 -0300 Subject: [PATCH] Add support for holiday as a function --- lib/business-hours.js | 8 +++++++- test/spec.business-hours.js | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/business-hours.js b/lib/business-hours.js index 01f3789..86099fc 100644 --- a/lib/business-hours.js +++ b/lib/business-hours.js @@ -8,6 +8,10 @@ function getLocaleData(key) { return moment.localeData()['_' + key]; } +function conditionalMatch(d, today, payload) { + return typeof payload === "function" ? payload(d, today) : minimatch(today, payload); +} + function openingTimes(d) { d = d.clone(); var hours = getLocaleData('workinghours'); @@ -214,9 +218,11 @@ moment.fn.isWorkingTime = function isWorkingTime(opts) { moment.fn.isHoliday = function isHoliday() { var isHoliday = false, + d = this, today = this.format('YYYY-MM-DD'); (getLocaleData('holidays') || []).forEach(function (holiday) { - if (minimatch(today, holiday)) { + if (isHoliday) return + if (conditionalMatch(d, today, holiday)) { isHoliday = true; } }); diff --git a/test/spec.business-hours.js b/test/spec.business-hours.js index a55bd83..e9a8b31 100644 --- a/test/spec.business-hours.js +++ b/test/spec.business-hours.js @@ -913,6 +913,23 @@ describe('moment.business-hours', function () { moment('2019-12-25').isWorkingDay().should.be.false; }); + it('supports holidays as functions', function () { + moment.locale('en'); + moment.locale('en', { + holidays: [ + function(d) { + return d.month() === 4 && + d.day() === 0 && + d.week() === (d.clone().startOf('month').week() + 1) + }, + '2015-02-27', + '*-12-25' + ] + }); + moment('2021-05-08').isHoliday().should.be.false; + moment('2022-05-08').isHoliday().should.be.true; + }); + }); });