Human Readable Time (5 kyu): Codewars (TDD in JavaScript)
Feb 17, 2020 08:00 · 482 words · 3 minute read
Hi! Welcome to Codewars. In this series I’m going to solve TDD katas using JavaScript. If this is your first time here and you want to learn Frontend and JavaScript. Let’s solve today kata titled “Human Readable Time.” Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format: hours, minutes, seconds. Hours, padded to 2 digits. Minutes are the same. Seconds are the same. The maximum time never exceeds… Okay, you can find some examples in the text fixtures. Okay.
00:52 - Okay, for doing that, I need to get input seconds and divide them several times as following. Hours I obtained like this: seconds divided by 60 minutes * 60 seconds. Minutes I’ll take like this: seconds divided by 60 and get the reminder by 60. And seconds I will get like seconds (make it like this)… Seconds reminder 60 and the result should be always in the Range: 0 0 - 9 9. From 0 to 99. Let’s start as following. Define hours. Then minutes. Then seconds. Let’s review our result. Let’s consider the second case.
02:04 - Its 5 seconds should be converted to this string. We have 0 0 and 5. That’s okay as we expected. So I need to convert this float numbers into integers. It’s the first step and then extend it with a leading zero. If any. Let’s do that. ParseInt is here. And here. Add leading zeros. And here as well. Let’s review. Good. Let’s review all the cases. Oh, you see we need to cut this string into only two digits without this legend zero. Let’s add this to this string. Wrap it with brackets and slice to two digits from the end. So, it’s minus two. The same for minutes. Let’s review.
03:14 - What we have? Yes, now that’s correct and the same for seconds. Now I can join all these variables with colons. Return hours plus colon, plus minutes. Plus seconds. Let’s test. Good. Now let’s optimize the solution a little bit and make it a bit smaller, let’s convert this to an arrow function. Now let’s shift all variables into one “return”. And remove this keyword. Let’s try. Good. Now I can convert this expression into a string literal.
04:25 - However, I want to use an array here and join its elements using “join” method. Let’s do that as following. An array, its first element. Second element. And third one. Join it by colon. Let’s try. Good. It works. And even works for all the test cases. I liked. My code is available on GitHub. Documentation is available in the Internet. Follow the links if you’re eager to get more. If you like this video give it “thumbs up”, share it with your friends, subscribe to the channel and watch other episodes. Thanks for watching and dive deeper. .