Starting my JS project was a daunting task since we have had only been exposed to it for 3 weeks prior, as opposed to Ruby, where we have had 3 months in total.
Trying to think of a project that would only use one page and could not refresh (so that we can manipulate the DOM), I turned to creating an online quiz — a Harry Potter House sorting quiz! I used a Rails API I created and used JavaScript for the frontend.
static checkForEnd(){if (House.gryffindor >= 5 || House.slytherin >=5 || House.ravenclaw >= 5 || House.hufflepuff >= 5){debuggerUser.getSorting()} else {debuggerHouse.checkTies()}};
The logic behind it seemed pretty simple at first, until I had to think about when there would be “ties”. I decided to have the quiz end in 10 questions, but have extra questions if there was a tie. There were three different scenarios where it could go:
- In the first round of questioning, the user had no ties for the “winner” house, so 5 or more selections related to that House. Automatically, it would take those selections and process the percentage of the inputed answers to give the user their “house percentages”.
- If there was no automatic winner (equal to, or grater than 5), I had to check to see if there was an actual winner or if there was a tie (ie. [4, 4, 1, 1]), or if it was a winner (ie. [4, 3, 2, 1]). If there is a winner, I had to make a “POST” request via ‘fetch()’ to the backend where I had a method to sort the percentages for the current user.
def housingnew_array = []house = User.current_user.houseshouse.each do |h|new_array << h.nameendhuf = new_array.count("Hufflepuff")sly = new_array.count("Slytherin")gry = new_array.count("Gryffindor")rav = new_array.count("Ravenclaw")if house.count != 0huf_percent = ((huf * 100) / house.count)sly_percent = (sly * 100) / house.countgry_percent = (gry * 100) / house.countrav_percent = (rav * 100) / house.countelsehuf_percent = 0sly_percent = 0gry_percent = 0rav_percent = 0endreturn {hufflepuff: huf_percent, slytherin: sly_percent, gryffindor: gry_percent, ravenclaw: rav_percent}end
3. If it was a tie, I would need to keep appending extra questions and checking after each one if there was a winner, which I handled in the frontend.
static checkTies(){const sumHouse = [House.gryffindor, House.slytherin, House.hufflepuff, House.ravenclaw]const winner = Math.max(...sumHouse)if (House.gryffindor == House.slytherin && House.gryffindor == winner || House.gryffindor == House.ravenclaw && House.gryffindor == winner|| House.gryffindor == House.hufflepuff && House.gryffindor == winner || House.slytherin == House.ravenclaw && House.slytherin == winner ||House.slytherin == House.hufflepuff && House.slytherin == winner || House.hufflepuff == House.ravenclaw && House.ravenclaw == winner){
Now that I know these bits of code are functional, I can start on refactoring them so that they become more DRY.