( duration: Duration, options?: FormatDurationOptions, )
| 84 | * //=> '2 years, 9 months, 3 weeks' |
| 85 | */ |
| 86 | export function formatDuration( |
| 87 | duration: Duration, |
| 88 | options?: FormatDurationOptions, |
| 89 | ): string { |
| 90 | const defaultOptions = getDefaultOptions(); |
| 91 | const locale = options?.locale ?? defaultOptions.locale ?? defaultLocale; |
| 92 | const format = options?.format ?? defaultFormat; |
| 93 | const zero = options?.zero ?? false; |
| 94 | const delimiter = options?.delimiter ?? " "; |
| 95 | |
| 96 | if (!locale.formatDistance) { |
| 97 | return ""; |
| 98 | } |
| 99 | |
| 100 | const result = format |
| 101 | .reduce((acc, unit) => { |
| 102 | const token = `x${unit.replace(/(^.)/, (m) => |
| 103 | m.toUpperCase(), |
| 104 | )}` as FormatDistanceToken; |
| 105 | const value = duration[unit]; |
| 106 | if (value !== undefined && (zero || duration[unit])) { |
| 107 | return acc.concat(locale.formatDistance(token, value)); |
| 108 | } |
| 109 | return acc; |
| 110 | }, [] as string[]) |
| 111 | .join(delimiter); |
| 112 | |
| 113 | return result; |
| 114 | } |
no test coverage detected