How much can you optimize this Javascript code?

Recently I had a situation where a colleague had to use the YouTube API to retrieve video information like the title, thumbnail and duration. My part on that was to review his code.

All was good, until we reach the duration parse 💥.
Youtube retrieved the duration using this format:

or worse, inconsistent;

All we want is the integer of the duration in seconds, what a mess!
Maybe not so messy if you consider this is actually the ISO 8601.

But definitely not as messy as my colleague’s solution to parse this 😎
No offense!

Let’s fix this with some cool maps and reduces?

Let’s start by a better regex, to retrieve a consistent array of hours, minutes and seconds, independently on the string has it or not.

That’s the way, an array with everything in place.

Moving on to Math, now the idea is to multiply the seconds for 60, minutes for 60*60 and hours for 60*60*60 . Do you see the pattern? 60 ** 0, 60 ** 1 and 60 ** 2 , 60 to the power of the index?

So the first thing is to reverse the array, to get seconds in the first index i = 0, minutes in second i = 1 and hours in third i = 2.

Now let’s map those numbers, first we parseInt them and then the number times 60 to the power of i.

The math is done.
Now we just need to reduce that array to it’s sum.

Don’t you love when you manage to both improve code readability and maintenance?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store