From 30fc6245da3efe4212644f891cb7184d86b0b7db Mon Sep 17 00:00:00 2001 From: Jean Augusto Silva Date: Tue, 25 May 2021 14:24:08 -0300 Subject: [PATCH] Add previous business day --- README.md | 4 ++++ lib/index.js | 17 +++++++++++++++++ test/query.js | 7 +++++++ 3 files changed, 28 insertions(+) diff --git a/README.md b/README.md index cad5322..7971e0c 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,10 @@ Returns if the supplied date is a business day. Returns the next business day after `day`. +## previousBusinessDay(country, date, options) + +Returns the previous business day before `day`. + # License Check [here](LICENSE). diff --git a/lib/index.js b/lib/index.js index fefd344..88fdcdf 100644 --- a/lib/index.js +++ b/lib/index.js @@ -73,6 +73,23 @@ exports.nextBusinessDay = function(country, anchorDate, options) { } }; +exports.previousBusinessDay = function(country, anchorDate, options) { + const day = moment(sanitizeDateInput(anchorDate)).subtract(1, 'd'); + + return iterate(day); + + function iterate(day) { + return exports.isBusinessDay(country, day, options) + .then(function(isBusinessDay) { + if (isBusinessDay) { + return day.toDate(); + } + + return iterate(day.subtract(1, 'd')); + }); + } +}; + function getDateFromInformation(info, date) { var key = date.format('YYYY-MM-DD'); diff --git a/test/query.js b/test/query.js index 0a0279a..3a8816a 100644 --- a/test/query.js +++ b/test/query.js @@ -30,5 +30,12 @@ describe('Query', function() { return expect(bm.nextBusinessDay('brazil', new Date(2016, 1, 5, 10))).to.eventually.eql(new Date(2016, 1, 10, 10)); }); }); + + describe('previousBusinessDay', function() { + it('should return the correct day', function() { + return expect(bm.previousBusinessDay('brazil', new Date(2021, 5, 4, 10))) + .to.eventually.eql(new Date(2021, 5, 2, 10)); + }); + }); });