Closers Refactor

How I added 50+ lines to my JavaScript code and made it more readable.

Closers Refactor

Backstory

I made a click speed testing web app that updates a scatterplot with points and a regression line on the page.

Here is the GitHub for this app where you can read more about some challenges I faced while making it as well as take a look at the code.

clicker.gif

I think it's pretty cool and I spent probably over 20 hours working on it. I definitely want to write a post on how I made it at some point, but this is not that post.

This post is about how I added 50+ commented-out lines to that code in an effort to make it more readable and understandable. I probably could have done better as well.

I realized I needed to do this when I tried showing someone my code and it was tough for me to even remember what each part represented and what each function accomplished.

Below are two examples of how adding comments made my functions more understandable.

Start Game Before:


function startGame() {
    duration = Number(select.value);
    hide(startBtn);
    score = 0;
    ended = false;

    startTime = new Date().getTime();

    let timerId = setInterval(function () {
        let total = (new Date().getTime() - startTime) / 1000;

        if (total < duration) {
            timerTxt.textContent = total.toFixed(3);
            clicksTxt.textContent = (score / total).toFixed(2);
        } else {
            ended = true;
            clearInterval(timerId);

            endGame();
        }
    }, 1);
}

Okay, so based on the name of this function we can tell it is the function that starts the game, but what does each part do????????????????????

Start Game After:

//this is the function that starts each round
function startGame() {
    //set the time to the value that the user selects
    duration = Number(select.value);
    hide(startBtn);
    //resets the score to 0
    score = 0;
    ended = false;
    //grabs the current time
    startTime = new Date().getTime();
    //this is the function that is running during the game
    let timerId = setInterval(function () {
        let total = (new Date().getTime() - startTime) / 1000;
        //if the game is still going, update the time and the score in the DOM
        if (total < duration) {
            timerTxt.textContent = total.toFixed(3);
            clicksTxt.textContent = (score / total).toFixed(2);
            //if the game has ended call the end game function
        } else {
            ended = true;
            clearInterval(timerId);

            endGame();
        }
    }, 1);
}

The comments make it a bit more clear, although admittedly not perfect. I feel confident that I could explain each part of this more easily than I could before.

End Game Before:

function endGame() {
    data2.splice(0, 1);

    let clicksBySeconds = (score / duration).toFixed(2);
    timerTxt.textContent = duration.toFixed(3);
    clicksTxt.textContent = clicksBySeconds;
    gameCount++;
    removeData(myChart);
    addData(myChart, "Clicks Per Second", { x: duration, y: score });
    lineData.push([duration, score]);

    show(startBtn);

    setTimeout(function () {
        alert(
            "You made " +
                score +
                " clicks in " +
                duration +
                " seconds. It is " +
                clicksBySeconds +
                " clicks per second. Try again!"
        );
    }, 10);
    predict();
    updateDataTwo();
    myChart.update();
}

End Game After:

function endGame() {
//tbh idk what this does, when I commented it out my app still worked but I am afraid to fully delete it, so it stays
    data2.splice(0, 1);
    //grabs the clickers per second and puts it in a variable
    let clicksBySeconds = (score / duration).toFixed(2);
    timerTxt.textContent = duration.toFixed(3);
    clicksTxt.textContent = clicksBySeconds;
    //increments the gameCount variable(this is used to decide whether to use the unit rate or linear regression to make a prediction)
    gameCount++;
    //this removes all of the points that were placed on the chart during the round
    removeData(myChart);
    //this places one point on the chart
    addData(myChart, "Clicks Per Second", { x: duration, y: score });
    //this adds the data to the dataset that the regression line uses
    lineData.push([duration, score]);
    //this shows the start button again so the user can start another round
    show(startBtn);
    //this alerts the user their score, it uses set timeout so that the DOM has a chance to refresh with the score before the alert pops up
    setTimeout(function () {
        alert(
            "You made " +
                score +
                " clicks in " +
                duration +
                " seconds. It is " +
                clicksBySeconds +
                " clicks per second. Try again!"
        );
    }, 10);
    //this runs the predict function which updates the DOM with a prediction based on the users previous scores
    predict();
    //this updates the dataset to plot the line of regression on the chart
    updateDataTwo();
    //this updates the chart to show all of the changes made to the data sets, both for the individual points and the line of regression
    myChart.update();
    //this shows the start button again so the user can start another round
    show(startBtn);
}

Again, while not perfect, I feel like the after is much more understandable for both me and another person who was not previously familiar with the code.

Why did I do this??

The main reason is readability and understandability(is this a word??) for both me and others. I wrote this code maybe a month or so ago and some of it is tough for me to remember the purpose of.

I hope this showed you that adding comments to your code can help both you and others understand your code better. I am sure it's best to add comments while you are writing the code, but if you are like me and just want to write the code to get it to work and didn't write comments initially, you should still go back after(even now) and add the comments.

As the saying goes, “The best time to plant a tree was 20 years ago. The second best time is now.”