Skip to content

Commit

Permalink
fix: add BigIntSupport plugin (#2087)
Browse files Browse the repository at this point in the history
  • Loading branch information
iamkun authored Oct 21, 2022
1 parent 7ae1a1d commit f6dce48
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/plugin/bigIntSupport/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// eslint-disable-next-line valid-typeof
const isBigInt = num => typeof num === 'bigint'
export default (o, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date } = cfg
if (isBigInt(date)) {
return Number(date)
}
return date
}

const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}


const oldUnix = dayjs.unix
dayjs.unix = function (timestamp) {
const ts = isBigInt(timestamp) ? Number(timestamp) : timestamp
return oldUnix(ts)
}
}
30 changes: 30 additions & 0 deletions test/plugin/bigIntSupport.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import bigIntSupport from '../../src/plugin/bigIntSupport'

dayjs.extend(bigIntSupport)

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

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

/* global BigInt */

it('Parse BigInt ts and tsms', () => {
const tsms = 1666310421101
const tsmsBig = BigInt(tsms)
const ts = 1666311003
const tsBig = BigInt(ts)
const momentTsms = moment(tsms)
const momentTs = moment.unix(ts)
expect(dayjs(tsms).valueOf()).toBe(momentTsms.valueOf())
expect(dayjs(tsms).valueOf()).toBe(dayjs(tsmsBig).valueOf())
expect(dayjs.unix(ts).valueOf()).toBe(momentTs.valueOf())
expect(dayjs.unix(tsBig).valueOf()).toBe(dayjs.unix(tsBig).valueOf())
})

11 changes: 11 additions & 0 deletions types/plugin/bigIntSupport.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { PluginFunc } from 'dayjs'

declare module 'dayjs' {
interface ConfigTypeMap {
bigIntSupport: BigInt
}
export function unix(t: BigInt): Dayjs
}

declare const plugin: PluginFunc
export = plugin

0 comments on commit f6dce48

Please sign in to comment.