devpapa

Merry JavaScriptmas

I am terrible at things that require long streaks of consistency. I just can't do it, but I will try. I will make the effort regardless.

December is the month with a lot of advent activities. 24 days of X, where X can be anything. I've joined adventofcode in the past but well you can guess what happened.

This year, I joined the Scrimba community's advent event; JavaScriptmas. It features 24 days of JavaScript problems to solve with a price at the end. If you win, you get $1,000 and a lifetime Scrimba Pro membership. This may be the hook I have been missing from these efforts; a reason to keep going, a prize at the end.

The code is pretty beginner level, but it does force you to apply your JavaScript knowledge to solve them. One benefit of being involved in this event is seeing how other people solve the same problem. I've been impressed by the different solutions posted on the Scrimba Discord.

Here's an example:

Day 8 has a challenge to check if a time is valid and return true if it is, and false if it is not. For example "23:59" is a valid time but "12:76" is not.

Here is my solution:

function validTime(str) {
    const [hour, min] = str.split(':')
    const isValidHour = parseInt(hour, 10) >= 0 &&
        parseInt(hour, 10) <= 23 ? true : false 
    const isValidMin = parseInt(min, 10) >= 0 &&
        parseInt(min, 10) <= 59 ? true : false

  return isValidHour && isValidMin ? true : false 
}

Not bad, I thought. Quite ugly, but who cares? It works!

Now compare this solution from Anubhav on Discord:

function validTime(str) {
    let [hours, minutes] = str.split(':')
    return (hours >= 0 && hours < 24) && (minutes >= 0 && minutes < 60)
}

How elegant. I'm in love.

Or this one liner from another person:

const validTime = (str) => str.split(":").every( (t, i) => t >= 0 && i==0? t <= 23 : t <= 59 );

This is good but to my eye not every readable. However I liked that he solved the problem in one line. I like this code also because it introduced me to Array.prototype.every(). I have never used it or heard of it.

Now I wish every month has a 24 day coding challenge. Yes, yes I know of project euler, et al but the kick, the prize at the end is missing from all these efforts.

What are you working on this December?

#code #javascript #scrimba