From be505c2c540261027342cecc55d8919a3d18d893 Mon Sep 17 00:00:00 2001 From: iamkun Date: Tue, 13 Oct 2020 16:10:46 +0800 Subject: [PATCH] fix: add arraySupport plugin (#1129) --- src/plugin/arraySupport/index.js | 25 +++++++++++++++ test/plugin/arraySupport.test.js | 52 ++++++++++++++++++++++++++++++++ types/plugin/arraySupport.d.ts | 4 +++ 3 files changed, 81 insertions(+) create mode 100644 src/plugin/arraySupport/index.js create mode 100755 test/plugin/arraySupport.test.js create mode 100755 types/plugin/arraySupport.d.ts diff --git a/src/plugin/arraySupport/index.js b/src/plugin/arraySupport/index.js new file mode 100644 index 000000000..df43727ff --- /dev/null +++ b/src/plugin/arraySupport/index.js @@ -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) + } +} diff --git a/test/plugin/arraySupport.test.js b/test/plugin/arraySupport.test.js new file mode 100755 index 000000000..dc5dda7ad --- /dev/null +++ b/test/plugin/arraySupport.test.js @@ -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()) + }) + }) +}) diff --git a/types/plugin/arraySupport.d.ts b/types/plugin/arraySupport.d.ts new file mode 100755 index 000000000..30ec75e5d --- /dev/null +++ b/types/plugin/arraySupport.d.ts @@ -0,0 +1,4 @@ +import { PluginFunc } from 'dayjs' + +declare const plugin: PluginFunc +export = plugin