console.log(["Good Morning", "Good Afternoon", "Good Evening"][~~(new Date().getHours() / 8)]);
Code Golf!
How this works:
You don't need to create a new Date object and stash it in a variable if you are just getting the hours. So you can do: new Date().getHours()
.
It also turns out, that you can place your messages in an Array and select the message you want like: var arr = ["Good Morning", "Good Afternoon", "Good Evening"]; console.log(arr[2]);
. But you don't need to stash the array in a variable to get the message. You can do this: ["Good Morning", "Good Afternoon", "Good Evening"][2]
. Sure, it looks a little weird, but it's saying, "Hey, here's an array of strings, get me the one at index 2."
So how to get the hours and turn it into 0, 1 or 2 (our indexes)? Well, take the hours and divide by 8. That will get you close. Say it's 7:30 am. You take 7 / 8 and get 0.875. That isn't an index. We need to round down. So we can do Math.floor(7/8)
and we get 0.
We can feed THAT (0
) to our array and get Good Morning
. Cool. Math.floor
is too many characters to type and I'm lazy. There's a Javascript hack using bitwise operators explained here. Basically ~~
does a Math.floor
. So we can cheat and do ~~(new Date().getHours() / 8)
to turn the hours into 0
, 1
, or 2
.
Take that result, get our string out of our array and smash the entire thing into console.log.