Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve nextDay implementation #2524

Merged
merged 4 commits into from Jul 23, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 9 additions & 16 deletions src/nextDay/index.ts
@@ -1,10 +1,8 @@
import requiredArgs from '../_lib/requiredArgs/index'
import getDay from '../getDay'
import addDays from '../addDays'
import getDay from '../getDay'
import toDate from '../toDate'
import { Day } from '../types'

const baseMap = [7, 6, 5, 4, 3, 2, 1]
import requiredArgs from '../_lib/requiredArgs/index'

/**
* @name nextDay
Expand All @@ -29,18 +27,13 @@ const baseMap = [7, 6, 5, 4, 3, 2, 1]
* const result = nextDay(new Date(2020, 2, 21), 2)
* //=> Tue Mar 24 2020 00:00:00
*/
export default function nextDay(date: Date | number, day: Day): Date {
export default function nextDay(dirtyDate: Date | number, day: Day): Date {
requiredArgs(2, arguments)
const map = genMap(day)
return addDays(toDate(date), map[getDay(toDate(date))])
}

function genMap(daysToMove: number): number[] {
if (daysToMove === 0) {
return baseMap
} else {
const mapStart = baseMap.slice(-daysToMove)
const mapEnd = baseMap.slice(0, baseMap.length - daysToMove)
return mapStart.concat(mapEnd)
}
const date = toDate(dirtyDate)

let delta = day - getDay(date)
if (delta <= 0) delta += 7

return addDays(date, delta)
}