Skip to content

Commit

Permalink
Convert sub to TypeScript (date-fns#2594)
Browse files Browse the repository at this point in the history
Co-authored-by: Tan75 <[email protected]>
Co-authored-by: Sasha Koss <[email protected]>
  • Loading branch information
3 people authored Sep 7, 2021
1 parent 4903798 commit 7b86bcd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
9 changes: 6 additions & 3 deletions src/sub/index.js → src/sub/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import subDays from '../subDays/index'
import subMonths from '../subMonths/index'
import toDate from '../toDate/index'
import { Duration } from '../types'
import requiredArgs from '../_lib/requiredArgs/index'
import toInteger from '../_lib/toInteger/index'

Expand Down Expand Up @@ -43,7 +43,10 @@ import toInteger from '../_lib/toInteger/index'
* })
* //=> Mon Sep 1 2014 10:19:50
*/
export default function sub(dirtyDate, duration) {
export default function sub(
date: Date | number,
duration: Duration
): Date {
requiredArgs(2, arguments)

if (!duration || typeof duration !== 'object') return new Date(NaN)
Expand All @@ -57,7 +60,7 @@ export default function sub(dirtyDate, duration) {
const seconds = duration.seconds ? toInteger(duration.seconds) : 0

// Subtract years and months
const dateWithoutMonths = subMonths(toDate(dirtyDate), months + years * 12)
const dateWithoutMonths = subMonths(date, months + years * 12)

// Subtract weeks and days
const dateWithoutDays = subDays(dateWithoutMonths, days + weeks * 7)
Expand Down
19 changes: 12 additions & 7 deletions src/sub/test.js → src/sub/test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @flow
/* eslint-env mocha */

import assert from 'power-assert'
Expand Down Expand Up @@ -62,8 +61,11 @@ describe('sub', () => {
})

it('implicitly converts number arguments', () => {
// $ExpectedMistake
const result = sub(new Date(2014, 8 /* Sep */, 1, 14), { hours: '4.2' })
const result = sub(
new Date(2014, 8 /* Sep */, 1, 14),
// @ts-expect-error
{ hours: '4.2' }
)
assert.deepEqual(result, new Date(2014, 8 /* Sep */, 1, 10))
})

Expand Down Expand Up @@ -92,13 +94,16 @@ describe('sub', () => {

it('returns `Invalid Date` if the given date is invalid', () => {
const result = sub(new Date(NaN), { hours: 5 })
assert(result instanceof Date && isNaN(result))
assert(result instanceof Date && isNaN(result.getTime()))
})

it('throws RangeError exception if passed Number as duration', () => {
// $ExpectedMistake
const result = sub(new Date(2014, 8, 1), 'wut')
assert(result instanceof Date && isNaN(result))
const result = sub(
new Date(2014, 8, 1),
// @ts-expect-error
'wut'
)
assert(result instanceof Date && isNaN(result.getTime()))
})

it('throws TypeError exception if passed less than 2 arguments', () => {
Expand Down

0 comments on commit 7b86bcd

Please sign in to comment.