Skip to content

Commit 2870a23

Browse files
committed
fix: Add plugin minMax to sopport .max .min
1 parent 317fd3e commit 2870a23

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/plugin/minMax/index.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export default (o, c, d) => {
2+
const sortBy = (method, dates) => {
3+
if (!dates.length) {
4+
return d()
5+
}
6+
if (dates.length === 1 && dates[0].length > 0) {
7+
[dates] = dates
8+
}
9+
let result
10+
[result] = dates
11+
for (let i = 1; i < dates.length; i += 1) {
12+
if (!dates[i].isValid() || dates[i][method](result)) {
13+
result = dates[i]
14+
}
15+
}
16+
return result
17+
}
18+
19+
d.max = function () {
20+
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
21+
return sortBy('isAfter', args)
22+
}
23+
d.min = function () {
24+
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
25+
return sortBy('isBefore', args)
26+
}
27+
}
28+

test/plugin/minMax.test.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import MockDate from 'mockdate'
2+
import dayjs from '../../src'
3+
import minMax from '../../src/plugin/minMax'
4+
5+
dayjs.extend(minMax)
6+
7+
beforeEach(() => {
8+
MockDate.set(new Date())
9+
})
10+
11+
afterEach(() => {
12+
MockDate.reset()
13+
})
14+
15+
const arg1 = dayjs('2019-01-01')
16+
const arg2 = dayjs('2018-01-01')
17+
const arg3 = dayjs('2017-01-01')
18+
const arg4 = dayjs('Invalid Date')
19+
20+
it('Return current time if no argument', () => {
21+
expect(dayjs.max().format())
22+
.toBe(dayjs().format())
23+
expect(dayjs.min().format())
24+
.toBe(dayjs().format())
25+
})
26+
27+
it('Compare between arguments', () => {
28+
expect(dayjs.max(arg1, arg2, arg3).format())
29+
.toBe(arg1.format())
30+
expect(dayjs.min(arg1, arg2, arg3).format())
31+
.toBe(arg3.format())
32+
})
33+
34+
it('Compare in array', () => {
35+
expect(dayjs.max([arg1, arg2, arg3]).format())
36+
.toBe(arg1.format())
37+
expect(dayjs.min([arg1, arg2, arg3]).format())
38+
.toBe(arg3.format())
39+
})
40+
41+
it('If Invalid Date return Invalid Date', () => {
42+
expect(dayjs.max(arg1, arg2, arg3, arg4).format())
43+
.toBe(arg4.format())
44+
expect(dayjs.min([arg1, arg2, arg3, arg4]).format())
45+
.toBe(arg4.format())
46+
})

types/plugin/minMax.d.ts

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { PluginFunc, ConfigType } from 'dayjs'
2+
3+
declare const plugin: PluginFunc
4+
export = plugin
5+
6+
declare module 'dayjs' {
7+
export function max(dayjs: Dayjs[]): Dayjs
8+
export function max(...dayjs: Dayjs[]): Dayjs
9+
export function min(dayjs: Dayjs[]): Dayjs
10+
export function min(...dayjs: Dayjs[]): Dayjs
11+
}

0 commit comments

Comments
 (0)