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

Improve formatDate, add more unit tests #1378

Merged
merged 1 commit into from
Nov 18, 2024
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
45 changes: 45 additions & 0 deletions packages/ripple-ui-core/src/lib/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { expect, describe, it } from '@jest/globals'

import { formatDate, distanceAsPercentage } from './helpers.js'

describe('Formatting a date', () => {
const raw = '2024-08-02T09:00:00+1000'

it('formats a date', () => {
expect(formatDate(raw)).toEqual('2 Aug 2024')
})

it('accepts custom date options', () => {
expect(
formatDate(raw, { day: 'numeric', month: 'short', year: '2-digit' })
).toEqual('2 Aug 24')
})

it('accepts custom date options with a non-default tz', () => {
expect(
formatDate(raw, {
dateStyle: 'medium',
timeZone: 'Japan',
timeStyle: 'short'
})
).toEqual('2 Aug 2024, 8:00 am')
})
})

describe('Transform distance to percentage', () => {
it('transforms a simple 100-scale', () => {
expect(distanceAsPercentage(35, 100)).toEqual(35)
})

it('transforms a point above ceil', () => {
expect(distanceAsPercentage(110, 100)).toEqual(100)
})

it('transforms a point below floor', () => {
expect(distanceAsPercentage(-80, 100)).toEqual(0)
})

it('transforms a complex scale', () => {
expect(distanceAsPercentage(29, 76)).toEqual(38.16)
})
})
17 changes: 13 additions & 4 deletions packages/ripple-ui-core/src/lib/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,24 @@ export const distanceAsPercentage = (point: number, total: number): number => {

export const formatDate = (
value: string | number | Date,
options: Intl.DateTimeFormatOptions = {}
options: Intl.DateTimeFormatOptions | undefined = undefined
): string => {
const date = new Date(value)

const defaultOptions: Intl.DateTimeFormatOptions = { dateStyle: 'medium', timeZone: 'Australia/Melbourne' }
const defaultOptions: Intl.DateTimeFormatOptions = {
dateStyle: 'medium',
timeZone: 'Australia/Melbourne'
}

options = { ...defaultOptions, ...options }
// Set default TZ
if (options && !options.timeZone) {
options.timeZone = 'Australia/Melbourne'
}

return new Intl.DateTimeFormat('en-AU', options).format(date)
return new Intl.DateTimeFormat(
'en-AU',
options ? options : defaultOptions
).format(date)
}

export { formatDateRange } from './formatDateRange'