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

fix: add arraySupport plugin #1129

Merged
merged 2 commits into from
Oct 13, 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
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