Skip to content

Instantly share code, notes, and snippets.

@arx8x
Last active September 14, 2021 15:00
Show Gist options
  • Save arx8x/cc5264d791d74680df5e3e6a39295f2d to your computer and use it in GitHub Desktop.
Save arx8x/cc5264d791d74680df5e3e6a39295f2d to your computer and use it in GitHub Desktop.
math operations on time
enum TimeDuration
{
case days(_: UInt)
case hours(_: UInt)
case minutes(_: UInt)
case seconds(_: UInt)
case muxed([TimeDuration])
case zero
var rawValue: UInt
{
switch self
{
case .days(let count):
return count * 86400
case .hours(let count):
return count * 3600
case .minutes(let count):
return count * 60
case .seconds(let count):
return count
case .muxed(let list):
return list.reduce(0){ $0 + $1.rawValue }
default:
return 0
}
}
init(seconds: UInt)
{
var arr: [TimeDuration] = []
// wish I knew how to implement CaseIterable conformance to this enum, so I could do this cleaner
let divisibles: [UInt] = [TimeDuration.days(1), TimeDuration.hours(1), TimeDuration.minutes(1), TimeDuration.seconds(1)].map{ $0.rawValue }
var reduced = seconds
for (index, divisible) in divisibles.enumerated()
{
let result = reduced / divisible
reduced %= divisible
if result <= 0 { continue }
switch index
{
case 0:
arr.append(.days(result))
break
case 1:
arr.append(.hours(result))
break
case 2:
arr.append(.minutes(result))
break
case 3:
arr.append(.seconds(result))
break
default:
break
}
}
self = .muxed(arr)
}
static func ==(l: TimeDuration, r: TimeDuration) -> Bool
{
return l.rawValue == r.rawValue
}
static func >(l: TimeDuration, r: TimeDuration) -> Bool
{
return l.rawValue > r.rawValue
}
static func < (l: TimeDuration, r: TimeDuration) -> Bool
{
return l.rawValue < r.rawValue
}
static func +(l: TimeDuration, r: TimeDuration) -> TimeDuration
{
let x = l.rawValue + r.rawValue
return .init(seconds: x)
}
static func -(l: TimeDuration, r: TimeDuration) -> TimeDuration
{
let x = l.rawValue - r.rawValue
return .init(seconds: x)
}
static func *(l: TimeDuration, r: TimeDuration) -> TimeDuration
{
let x = l.rawValue * r.rawValue
return .init(seconds: x)
}
static func /(l: TimeDuration, r: TimeDuration) -> TimeDuration
{
let x = l.rawValue / r.rawValue
return .init(seconds: x)
}
}
print(TimeDuration.hours(20) > TimeDuration.muxed([.hours(19), .minutes(60)])) // false
print(TimeDuration(seconds: 2500)) // muxed([__lldb_expr_96.TimeDuration.minutes(41), __lldb_expr_96.TimeDuration.seconds(40)])
print(TimeDuration.hours(2) + .days(2) - .minutes(60)) // muxed([__lldb_expr_96.TimeDuration.days(2), __lldb_expr_96.TimeDuration.hours(1)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment