export interface IDuration {
readonly milliseconds: number
readonly seconds: number
readonly minutes: number
readonly hours: number
readonly days: number
}
export class Duration implements IDuration {
readonly total: number
constructor(input: IDuration) {
const { days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0 } = input
this.total = days + hours + minutes + seconds + milliseconds
}
static of(input: Partial<IDuration>): Duration {
const { days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0 } = input
return new Duration({
days: days * 86400000,
hours: hours * 3600000,
minutes: minutes * 60000,
seconds: seconds * 1000,
milliseconds,
})
}
add(other: Duration): Duration {
return Duration.of({ milliseconds: this.total + other.total })
}
subtract(other: Duration): Duration {
return Duration.of({ milliseconds: this.total - other.total })
}
get days() {
return Math.floor(this.total / 86400000)
}
get hours() {
return Math.floor(this.total / 3600000)
}
get minutes() {
return Math.floor(this.total / 60000)
}
get seconds() {
return Math.floor(this.total / 1000)
}
get milliseconds() {
return this.total
}
}