Skip to content

Commit

Permalink
Fix addBusinessDays when input date is a weekend day (#1628)
Browse files Browse the repository at this point in the history
  • Loading branch information
Matsuuu authored and kossnocorp committed Jul 17, 2020
1 parent 02f1ead commit d098e19
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/addBusinessDays/index.js
Expand Up @@ -2,6 +2,8 @@ import isWeekend from '../isWeekend/index.js'
import toDate from '../toDate/index.js'
import toInteger from '../_lib/toInteger/index.js'
import requiredArgs from '../_lib/requiredArgs/index.js'
import isSunday from '../isSunday/index.js'
import isSaturday from '../isSaturday/index.js'

/**
* @name addBusinessDays
Expand All @@ -25,6 +27,7 @@ export default function addBusinessDays(dirtyDate, dirtyAmount) {
requiredArgs(2, arguments)

const date = toDate(dirtyDate)
const startedOnWeekend = isWeekend(date)
const amount = toInteger(dirtyAmount)

if (isNaN(amount)) return new Date(NaN)
Expand All @@ -44,6 +47,16 @@ export default function addBusinessDays(dirtyDate, dirtyAmount) {
if (!isWeekend(date)) restDays -= 1
}

// If the date is a weekend day and we reduce a dividable of
// 5 from it, we land on a weekend date.
// To counter this, we add days accordingly to land on the next business day
if (startedOnWeekend && isWeekend(date) && amount !== 0) {
// If we're reducing days, we want to add days until we land on a weekday
// If we're adding days we want to reduce days until we land on a weekday
if (isSaturday(date)) date.setDate(date.getDate() + (sign < 0 ? 2 : -1))
if (isSunday(date)) date.setDate(date.getDate() + (sign < 0 ? 1 : -2))
}

// Restore hours to avoid DST lag
date.setHours(hours)

Expand Down
7 changes: 7 additions & 0 deletions src/addBusinessDays/test.js
Expand Up @@ -81,4 +81,11 @@ describe('addBusinessDays', function() {
assert.throws(addBusinessDays.bind(null), TypeError)
assert.throws(addBusinessDays.bind(null, 1), TypeError)
})
it('starting from a weekend day should land on a weekday when reducing a divisible by 5', function() {
const substractResult = addBusinessDays(new Date(2019, 7, 18), -5)
assert.deepEqual(substractResult, new Date(2019, 7, 12))

const addResult = addBusinessDays(new Date(2019, 7, 18), 5)
assert.deepEqual(addResult, new Date(2019, 7, 23))
})
})

0 comments on commit d098e19

Please sign in to comment.