CodeSOD: Scheduling your Terns
Mike has a co-worker who's better at Code Golf than I am. They needed to generate a table with 24 column headings, one for each hour of the day, formatted in HAM- the hour and AM/PM. As someone bad at code golf, my first instinct is honestly to use two for loops, but in practice I'd probably do a 24 iteration loop with a branch to decide if it's AM/PM and handle it appropriately, as well as a branch to handle the fact that hour 0 should be printed as 12.
Which, technically, more or less what Mike's co-worker did, but they did in in golf style, using PHP.
<tr><?php for ($i = 0; $i < 24; $i++) {echo '<th><div>'.($i%12?$i%12:12).($i/12>=1?'pm':'am').'</div></th><th></th>';}?></tr>
This is code written by someone who just recently discovered ternaries. It's not wrong. It's not even a complete and utter disaster. It's just annoying. Maybe I'm jealous of their code golf skills, but this is the kind of code that makes me grind my teeth when I see it.
It's mildly... clever? $i%12?$i%12:12- i%12 will be zero when i is 12, which is false, and our false branch says to output 12, and our true branch says to output i%12. So that's sorted, handles all 24 hours of the day.
Then, for AM/PM, they ($i/12>=1?'pm':'am')- which also works. Values less than 12 fail the condition, so our false path is 'am', values greater than 12 will get 'pm'.
But wait a second. We don't need the >= or the division in there. This could just be ($i>11?'pm':'am').
Well, maybe I am good at Code Golf.
I still hate it.
[Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!