Have you ever found great pleasure from overcoming a difficult challenge? I know I have. For me, it’s especially true when solving a puzzle or finding a solution to a problem. For that very reason, I decided to write my first blog post about a coding challenge from Codewars and run you through my thought process.
A quick synopsis of the challenge, you must write a method that takes in an integer as an argument. The method must put out a string, in a human readable time format. This means that it must be grammatically correct to pass this kata. Additionally, we cannot have any units of time that have a value of zero in our string. Fortunately for us, we can pseudocode our way on the right track. For me it looked a little something like this.
So, right off the bat we know we have to convert seconds into several other units of time. There’s a couple of different ways we could go about this but ultimately, I decided to use #divmod to accomplish this task.
If you aren’t familiar with #divmod, don’t worry neither was I, until recently. Simply put in line one, I’m taking the s(seconds) and using #divmod to both divide and modulo them by 60. The result? An array with both results. The division results are then equated to m(minutes), and the modulo results equated to s(seconds). I repeat this 3 more times to get my h(hours), d(days), and y(years). Now we’re ready for part two.
There was probably a much more efficient way I could have accomplished this but, this is the route I took. Here I created five simple if statements, that first check if the value of each variable is greater than zero. Followed by a simple ternary operator that will interpolate our values into our string, and it also determines if our string will be singular or plural. After all that it throws the results into our newly created t(time) array.
This is the final part of our solution that admit-ably took me the longest to complete. Basically, my if statement checks if the array we created is housing two or more strings and then adds commas to all of the strings that require them. If there are only two, then no commas will be added. Additionally, it also adds the “and” when needed. Finally, we simply join our array and we are done.
When we put it all together, we have our lean mean human readable duration formatting machine capable of taking any integer no matter how large and returning a formatted string like these.
Although I was definitely proud of myself for being able to complete this challenge, it was also very humbling. I got to compare my results with others, I was able to see how much I still have to learn and where I could potentially be if I continue to work hard and push myself.
On that note, I’d like to end this post by urging you to seek out your own challenges to overcome in hopes that you have a great experience like I did.