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

Allowing optional duration values in toSeconds #18

Merged
merged 2 commits into from
Nov 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@ const timePattern = `T(${numbers}H)?(${numbers}M)?(${numbers}S)?`
const iso8601 = `P(?:${weekPattern}|${datePattern}(?:${timePattern})?)`
const objMap = ['weeks', 'years', 'months', 'days', 'hours', 'minutes', 'seconds']

const defaultDuration = Object.freeze({
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0
})

/**
* The ISO8601 regex for matching / testing durations
*/
Expand All @@ -41,6 +51,8 @@ export const parse = durationString => {
* @return {Date} - The resulting end Date
*/
export const end = (duration, startDate) => {
duration = Object.assign({}, defaultDuration, duration)

// Create two equal timestamps, add duration to 'then' and return time difference
const timestamp = (startDate ? startDate.getTime() : Date.now())
const then = new Date(timestamp)
Expand All @@ -66,6 +78,8 @@ export const end = (duration, startDate) => {
* @return {Number}
*/
export const toSeconds = (duration, startDate) => {
duration = Object.assign({}, defaultDuration, duration)

const timestamp = (startDate ? startDate.getTime() : Date.now())
const now = new Date(timestamp)
const then = end(duration, now)
Expand Down
8 changes: 8 additions & 0 deletions test/iso8601-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,11 @@ test('expose vulnerable time calculation in toSeconds', t => {
t.is(sec, 0)
})
})

test('optional arguments for time calculation in toSeconds', t => {
const sec = toSeconds({
minutes: 3
})

t.is(sec, 180)
})