Created
September 13, 2023 20:08
-
-
Save dmmulroy/b26302ed80c8a3ec7e0b76be384e7dd2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Duration = { | |
years?: number | |
months?: number | |
weeks?: number | |
days?: number | |
hours?: number | |
minutes?: number | |
seconds?: number | |
} | |
export const Duration = { | |
MS_IN_DAY: milliseconds({ days: 1 }), | |
MS_IN_HOUR: milliseconds({ hours: 1 }), | |
MS_IN_MINUTE: milliseconds({ minutes: 1 }), | |
MS_IN_SECOND: milliseconds({ seconds: 1 }), | |
add(d1: Duration, d2: Duration): Duration { | |
return Duration.ofMilliseconds(milliseconds(d1) + milliseconds(d2)) | |
}, | |
equals(d1: Duration, d2: Duration): boolean { | |
return milliseconds(d1) === milliseconds(d2) | |
}, | |
gt(d1: Duration, d2: Duration): boolean { | |
return milliseconds(d1) > milliseconds(d2) | |
}, | |
gte(d1: Duration, d2: Duration): boolean { | |
return milliseconds(d1) >= milliseconds(d2) | |
}, | |
lt(d1: Duration, d2: Duration): boolean { | |
return milliseconds(d1) < milliseconds(d2) | |
}, | |
lte(d1: Duration, d2: Duration): boolean { | |
return milliseconds(d1) <= milliseconds(d2) | |
}, | |
ofMilliseconds(ms: number): Duration { | |
const days = Math.floor(ms / Duration.MS_IN_DAY) | |
ms -= days * Duration.MS_IN_DAY | |
const hours = Math.floor(ms / Duration.MS_IN_HOUR) | |
ms -= hours * Duration.MS_IN_HOUR | |
const minutes = Math.floor(ms / Duration.MS_IN_MINUTE) | |
ms -= minutes * Duration.MS_IN_MINUTE | |
const seconds = Math.floor(ms / Duration.MS_IN_SECOND) | |
ms -= seconds * Duration.MS_IN_SECOND | |
return { | |
days, | |
hours, | |
minutes, | |
seconds, | |
} | |
}, | |
subtract(d1: Duration, d2: Duration): Duration { | |
const delta = milliseconds(d1) - milliseconds(d2) | |
if (delta < 0) { | |
throw new Error( | |
"d1 is smaller than d2, can't produce a negative duration" | |
) | |
} | |
return Duration.ofMilliseconds(delta) | |
}, | |
toHumanString(d: Duration): string { | |
const formattedDuration = formatDuration(d, { delimiter: ', ' }) | |
const lastCommaIndex = formattedDuration.lastIndexOf(',') | |
if (lastCommaIndex === -1) { | |
return formattedDuration | |
} | |
return ( | |
formattedDuration.substring(0, lastCommaIndex) + | |
' and' + | |
formattedDuration.substring(lastCommaIndex + 1) | |
) | |
}, | |
toMilliseconds(d: Duration): number { | |
return milliseconds(d) | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment