Skip to content

Commit

Permalink
fix(useTimeAgo): rounding unit fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Dec 20, 2022
1 parent 9293c1b commit f40a021
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
9 changes: 9 additions & 0 deletions packages/core/useTimeAgo/index.test.ts
Expand Up @@ -249,6 +249,15 @@ describe('useTimeAgo', () => {
expect(useTimeAgo(changeTime, { rounding: 3 }).value).toBe('in 5.49 days')
})

test('rounding unit fallback', () => {
changeValue.value = getNeededTimeChange('month', 11.5)
expect(useTimeAgo(changeTime).value).toBe('next year')
expect(useTimeAgo(changeTime, { rounding: 'ceil' }).value).toBe('next year')
expect(useTimeAgo(changeTime, { rounding: 'floor' }).value).toBe('in 11 months')
expect(useTimeAgo(changeTime, { rounding: 1 }).value).toBe('in 0.9 year')
expect(useTimeAgo(changeTime, { rounding: 3 }).value).toBe('in 0.945 year')
})

test('custom units', () => {
changeValue.value = getNeededTimeChange('day', 14)
expect(useTimeAgo(changeTime).value).toBe('in 2 weeks')
Expand Down
11 changes: 9 additions & 2 deletions packages/core/useTimeAgo/index.ts
Expand Up @@ -168,8 +168,12 @@ export function foramtTimeAgo<UnitNames extends string = UseTimeAgoUnitNamesDefa
const diff = +now - +from
const absDiff = Math.abs(diff)

function getValue(diff: number, unit: UseTimeAgoUnit) {
return roundFn(Math.abs(diff) / unit.value)
}

function format(diff: number, unit: UseTimeAgoUnit) {
const val = roundFn(Math.abs(diff) / unit.value)
const val = getValue(diff, unit)
const past = diff > 0

const str = applyFormat(unit.name as UnitNames, val, past)
Expand All @@ -196,7 +200,10 @@ export function foramtTimeAgo<UnitNames extends string = UseTimeAgoUnitNamesDefa
return fullDateFormatter(new Date(from))
}

for (const unit of units) {
for (const [idx, unit] of units.entries()) {
const val = getValue(diff, unit)
if (val <= 0 && units[idx - 1])
return format(diff, units[idx - 1])
if (absDiff < unit.max)
return format(diff, unit)
}
Expand Down

0 comments on commit f40a021

Please sign in to comment.