Skip to content

Commit

Permalink
fix: add arraySupport plugin (#1129)
Browse files Browse the repository at this point in the history
  • Loading branch information
iamkun authored Oct 13, 2020
1 parent f56783e commit be505c2
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/plugin/arraySupport/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default (o, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date, utc } = cfg
if (Array.isArray(date)) {
if (utc) {
if (!date.length) {
return new Date()
}
return new Date(Date.UTC.apply(null, date))
}
if (date.length === 1) {
return dayjs(String(date[0])).toDate()
}
return new (Function.prototype.bind.apply(Date, [null].concat(date)))()
}
return date
}

const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}
}
52 changes: 52 additions & 0 deletions test/plugin/arraySupport.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import arraySupport from '../../src/plugin/arraySupport'
import utc from '../../src/plugin/utc'

dayjs.extend(utc)
dayjs.extend(arraySupport)

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

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

describe('parse empty array', () => {
it('local', () => {
expect(dayjs([]).format())
.toBe(moment([]).format())
})
it('utc', () => {
expect(dayjs.utc([]).format())
.toBe(moment.utc([]).format())
})
})

const testArrs = [
[2010, 1, 14, 15, 25, 50, 125],
[2010],
[2010, 6],
[2010, 6, 10]
]

describe('parse array local', () => {
testArrs.forEach((testArr) => {
it(testArr, () => {
expect(dayjs(testArr).format())
.toBe(moment(testArr).format())
})
})
})

describe('parse array utc', () => {
testArrs.forEach((testArr) => {
it(testArr, () => {
expect(dayjs.utc(testArr).format())
.toBe(moment.utc(testArr).format())
})
})
})
4 changes: 4 additions & 0 deletions types/plugin/arraySupport.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { PluginFunc } from 'dayjs'

declare const plugin: PluginFunc
export = plugin

0 comments on commit be505c2

Please sign in to comment.