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

feat: add normalize to duration to redistribute the unit values #2716

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
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
4 changes: 4 additions & 0 deletions src/plugin/duration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,10 @@ class Duration {
return wrapper(this.$ms, this)
}

normalize() {
return wrapper(this.$ms, this)
}

humanize(withSuffix) {
return $d()
.add(this.$ms, 'ms')
Expand Down
31 changes: 31 additions & 0 deletions test/plugin/duration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -309,3 +309,34 @@ describe('Format', () => {
.toBe('2/02.0002TEST9:09:6:06:8:08:5:05:1:01:010')
})
})

describe('Normalize units', () => {
[
['PT60S', 'PT1M'],
['PT120M', 'PT2H'],
['PT24H', 'P1D'],
['P30DT10H', 'P1M'],
['P31D', 'P1MT14H'],
['P12M', 'P1Y'],

['PT0.5M', 'PT30S'],
['PT0.5H', 'PT30M'],
['P0.5D', 'PT12H'],
['P0.5M', 'P15DT5H'],
['P0.5Y', 'P6M'],

['P1Y13M25DT25H61M65S', 'P2Y1M26DT2H2M5S']
].forEach(([input, output]) => {
test(`Normalize ${input} to ${output}`, () => {
const normalized = dayjs.duration(input).normalize()

expect(normalized.toISOString()).toBe(output)
})

test(`Clone ${input} to ${output}`, () => {
const cloned = dayjs.duration(input).clone()

expect(cloned.toISOString()).toBe(output)
})
})
})
4 changes: 3 additions & 1 deletion types/plugin/duration.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ declare namespace plugin {

clone(): Duration

normalize(): Duration

humanize(withSuffix?: boolean): string

milliseconds(): number
Expand Down Expand Up @@ -85,4 +87,4 @@ declare module 'dayjs' {
*/
export const duration: plugin.CreateDurationType;
export function isDuration(d: any): d is plugin.Duration
}
}