Catlog App Development Journal - #2 Challenges & Solutions

ยท

3 min read

Converting and calculating dates and durations

Challenge:

On the Add Cat Page, the user inputs the cat's birthday. However, when displaying cats' info, I want to show their age -- so no one needs to do math ๐Ÿ˜‰. How should I get the age of a cat from its birthday in format of 2011-12-31T00:00:00.000+00:00?

Solution:

In my Daily Task Heatmap project, I wrote a function in Javascript to get the date x-amount of years/months/days before today (now). Although it was a good coding practice, I don't want to have to code out the function again for this project. There must be a library that does this job.

After some Googling, I decided to give moment.js a try. Installation and importing was easy, and I figured out how to use it to solve my problem:

  getAgeFromBirthday: (birthday) => {
    let today = moment();
    let bday = moment(birthday, 'MM-YYYY');
    let duration = moment.duration(today.diff(bday));
    let years = duration.years();
    let months = duration.months();
    let age

    if (years == 0) {
      age = `${months} months old`
    } else if (months == 0) {
      age = `${years} years old`
    } else {
      age = `${years} years ${months} months old`
    }
    return age
  }

Abstraction and Separation of Concerns

Challenge:

The function above is 17 lines long, and I need to use it for multiple functions in two controller files (for individual Cat Profile Page, All Cats Page and User Profile Page). If I just copy/paste the code each time I call this function, my controller file will have too many lines of code and a lot of it being repetitive. Also, what if I want to change this function later on? I'll have to go to each controller function to update it, hoping I don't leave one behind.

Solution:

Thinking about the benefits of abstraction and separation of concerns, I moved this code into a new folder called helpers and created a utils.js file to "module.exports" it. And when every I need to call this function, I require it and it's now a one-liner.

Some interesting "experiments" that worked

Conditionals for html elements' attributes

When the user tries to edit a cat's profile, I want the edit form to show what the current values are. It's easy for an input with a type of text, but when it comes to a dropdown selection, I know I need to add the "select" attribute to the option that was previously chosen, but how should I handle this in EJS?

<select name="fixed">
    <option value="Yes" <% if(cat.fixed == 'Yes') { %>  selected <% } %> >Yes</option>
    <option value="No" <% if(cat.fixed == 'No') { %>  selected <% } %> >No</option> 
</select>
ย