https://kotlinlang.org logo
Title
e

Ellen Spertus

01/28/2020, 1:26 AM
Which is better?
// 1
val h = hour.toInt() + if (meridian.isNotEmpty() && meridian[0] == 'p') 12 else 0
or
//2
var h = hour.toInt()
if (meridian.isNotEmpty() && meridian[0] == 'p') h += 12
1️⃣ 3
c

Czar

01/28/2020, 5:54 PM
val h = hour.toInt() + meridian.toOffset()
fun Meridian.toOffset() = if(firstOrNull() == 'p') 12 else 0
If
Meridian
is actually a
String
make sure that the extension function is private, better yet I suggest using a wrapper class instead of
String
for better typesafety.
e

Ellen Spertus

01/28/2020, 6:04 PM
Thanks, @Czar!
meridian
(since renamed to
period
) is returned from
MatchResult.destructured
. It’s for either AM or PM.
c

Czar

01/28/2020, 6:28 PM
I see, then
val h = hour.toInt() + if (period.firstOrNull() == 'P') 12 else 0
would be my favourite. That said, midnight can be represented as 12 AM, and noon as 12 PM so this algorithm will return 12 for midnight and 24 for noon, I somehow doubt that that is the desired behaviour...
e

Ellen Spertus

01/28/2020, 6:30 PM
@Czar Thanks, I realized that the code has problems. My current version checks if
h < 12
before adding. Technically, 12 AM and 12 PM don’t exist and should be 12 midnight and 12 noon (respectively?). I’m planning to have a separate regex.
c

Czar

01/28/2020, 6:32 PM
Yeah, but real world, heh 🤷‍♂️
😀 1
e

Ellen Spertus

01/28/2020, 6:32 PM
Our work sure would be easier without users.
c

Czar

01/28/2020, 6:34 PM
😄 definitely. Interestingly if you check the link I've posted, even some dictionaries mention 12 AM meaning midnight and 12 PM meaning noon, so it's kinda not users' fault it's natural language... It's always hard to process...
e

Ellen Spertus

01/28/2020, 6:35 PM
Since 12 + epsilon PM is afternoon, it’s understandable that people consider 12 PM to be noon.
c

Czar

01/28/2020, 6:36 PM
That's exactly how I'm remembering it 😄 Those exercises with calculations on floats and doubles are paying off in everyday life 😄
e

Ellen Spertus

01/28/2020, 6:49 PM
😃 1