Skip to content

Commit

Permalink
fix: Add plugin minMax to sopport .max .min
Browse files Browse the repository at this point in the history
  • Loading branch information
iamkun committed Mar 28, 2019
1 parent 317fd3e commit 2870a23
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/plugin/minMax/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export default (o, c, d) => {
const sortBy = (method, dates) => {
if (!dates.length) {
return d()
}
if (dates.length === 1 && dates[0].length > 0) {
[dates] = dates
}
let result
[result] = dates
for (let i = 1; i < dates.length; i += 1) {
if (!dates[i].isValid() || dates[i][method](result)) {
result = dates[i]
}
}
return result
}

d.max = function () {
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
return sortBy('isAfter', args)
}
d.min = function () {
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
return sortBy('isBefore', args)
}
}

46 changes: 46 additions & 0 deletions test/plugin/minMax.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import MockDate from 'mockdate'
import dayjs from '../../src'
import minMax from '../../src/plugin/minMax'

dayjs.extend(minMax)

beforeEach(() => {
MockDate.set(new Date())
})

afterEach(() => {
MockDate.reset()
})

const arg1 = dayjs('2019-01-01')
const arg2 = dayjs('2018-01-01')
const arg3 = dayjs('2017-01-01')
const arg4 = dayjs('Invalid Date')

it('Return current time if no argument', () => {
expect(dayjs.max().format())
.toBe(dayjs().format())
expect(dayjs.min().format())
.toBe(dayjs().format())
})

it('Compare between arguments', () => {
expect(dayjs.max(arg1, arg2, arg3).format())
.toBe(arg1.format())
expect(dayjs.min(arg1, arg2, arg3).format())
.toBe(arg3.format())
})

it('Compare in array', () => {
expect(dayjs.max([arg1, arg2, arg3]).format())
.toBe(arg1.format())
expect(dayjs.min([arg1, arg2, arg3]).format())
.toBe(arg3.format())
})

it('If Invalid Date return Invalid Date', () => {
expect(dayjs.max(arg1, arg2, arg3, arg4).format())
.toBe(arg4.format())
expect(dayjs.min([arg1, arg2, arg3, arg4]).format())
.toBe(arg4.format())
})
11 changes: 11 additions & 0 deletions types/plugin/minMax.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PluginFunc, ConfigType } from 'dayjs'

declare const plugin: PluginFunc
export = plugin

declare module 'dayjs' {
export function max(dayjs: Dayjs[]): Dayjs
export function max(...dayjs: Dayjs[]): Dayjs
export function min(dayjs: Dayjs[]): Dayjs
export function min(...dayjs: Dayjs[]): Dayjs
}

0 comments on commit 2870a23

Please sign in to comment.