|
1 | | -import parse from 'parse-duration' |
| 1 | +import { Duration, DurationFormatter } from '@sapphire/duration' |
2 | 2 |
|
3 | | -parse[''] = parse['s']! |
4 | | -parse['mo'] = parse['M'] = parse['month']! |
| 3 | +const fmt = new DurationFormatter({ |
| 4 | + year: { |
| 5 | + DEFAULT: 'y', |
| 6 | + }, |
| 7 | + month: { |
| 8 | + DEFAULT: 'M', |
| 9 | + }, |
| 10 | + week: { |
| 11 | + DEFAULT: 'w', |
| 12 | + }, |
| 13 | + day: { |
| 14 | + DEFAULT: 'd', |
| 15 | + }, |
| 16 | + hour: { |
| 17 | + DEFAULT: 'h', |
| 18 | + }, |
| 19 | + minute: { |
| 20 | + DEFAULT: 'm', |
| 21 | + }, |
| 22 | + second: { |
| 23 | + DEFAULT: 's', |
| 24 | + }, |
| 25 | +}) |
5 | 26 |
|
6 | | -export const parseDuration = (duration: string, defaultUnit?: parse.Units) => { |
7 | | - const defaultUnitValue = parse['']! |
8 | | - if (defaultUnit) parse[''] = parse[defaultUnit]! |
9 | | - const result = parse(duration, 'ms') ?? Number.NaN |
10 | | - parse[''] = defaultUnitValue |
11 | | - return result |
| 27 | +export const parseDuration = (duration: string, defaultUnit = 's') => { |
| 28 | + // adds default unit to the end of the string if it doesn't have a unit |
| 29 | + // 100 -> 100s |
| 30 | + // 10m100 -> 10m100s |
| 31 | + // biome-ignore lint/style/noParameterAssign: this is fine |
| 32 | + if (/\d$/.test(duration)) duration += defaultUnit |
| 33 | + return new Duration(duration).offset |
12 | 34 | } |
13 | 35 |
|
14 | 36 | export const durationToString = (duration: number) => { |
15 | | - if (duration === 0) return '0s' |
16 | | - |
17 | | - const days = Math.floor(duration / (24 * 60 * 60 * 1000)) |
18 | | - const hours = Math.floor((duration % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)) |
19 | | - const minutes = Math.floor((duration % (60 * 60 * 1000)) / (60 * 1000)) |
20 | | - const seconds = Math.floor((duration % (60 * 1000)) / 1000) |
21 | | - |
22 | | - return `${days ? `${days}d` : ''}${hours ? `${hours}h` : ''}${minutes ? `${minutes}m` : ''}${ |
23 | | - seconds ? `${seconds}s` : '' |
24 | | - }` |
| 37 | + return fmt.format(duration, undefined, { |
| 38 | + left: '', |
| 39 | + }) |
25 | 40 | } |
0 commit comments