Creating a quiz game, how do I avoid code duplication in javascript?

Asked

Viewed 65 times

1

I am creating a simple game of selecting the correct answer, the basic structure is working, but I would like to improve my code, and learn to factor better.

Follows the passage that define the variables I use:


let pos = 0, test, test_status, question, choice, choices, chA, 
chB, chC, chD, chE, chF, chG, chH, chI, correct = 0, wrong = 0;

let questions = [
{
        question: "Qual dos dois filmes se refere a 'Jornada nas Estrelas'?",
        a: "Star Trek",
        b: "Star Wars",
        c: "ambas as respostas estāo corretas",
        d: "ambas as respostas estão incorretas",
        answer: "A"
},
{
        question: "A frase icônica: 'You bow to no one my friends', foi dito por qual personagem?",
        a: "Obi-Wan Kenobi",
        b: "Gandalf",
        c: "Tex Willer",
        d: "Aragorn",
        e: "Capitāo America",
        f: "Spock",
        g: "Nenhuma das opções acima",
        answer: "D"
}

And here the relevant code my question:

    question = questions[pos].question;
    chA = questions[pos].a;
    chB = questions[pos].b;
    chC = questions[pos].c;
    chD = questions[pos].d;
    chE = questions[pos].e;
    chF = questions[pos].f;
    chG = questions[pos].g;
    chH = questions[pos].h;
    chI = questions[pos].i;

    test.innerHTML = "<h3>"+question+"</h3>";

    test.innerHTML += "<label> <input type='radio' name='choices' value='A'> " + chA + "</label><br>";
    if (typeof chB !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='B'> " + chB + "</label><br>";
    if (typeof chC !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='C'> "+chC+"</label><br>";
    if (typeof chD !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='D'> " + chD + "</label><br>";
    if (typeof chE !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='E'> "+chE+"</label><br>";
    if (typeof chF !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='F'> "+chF+"</label><br>";
    if (typeof chG !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='G'> "+chG+"</label><br>";
    if (typeof chH !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='H'> "+chH+"</label><br>";
    if (typeof chI !== "undefined")
        test.innerHTML += "<label> <input type='radio' name='choices' value='I'> "+chI+"</label><br>";
    test.innerHTML += "<label></label><br>";
    test.innerHTML += "<button onclick='checkAnswer()'>Confirmar Resposta</button>";

My text editor complains of code duplication both at the initialization of variables chA, chB ... chI as in the part that creates the input element in HTML (innerHTML...). My question is, how should I proceed to eliminate this tangle of repetitive code, and put everything in a loop, for example?

One last detail: need to check every time if the variable in question is not Undefined to prevent the following from occurring:

exemplo

1 answer

1


    let pos = 0, test, test_status, question, choice, choices, chA, 
    chB, chC, chD, chE, chF, chG, chH, chI, correct = 0, wrong = 0;

    let questions = [
    {
            question: "Qual dos dois filmes se refere a 'Jornada nas Estrelas'?",
            a: "Star Trek",
            b: "Star Wars",
            c: "ambas as respostas estāo corretas",
            d: "ambas as respostas estão incorretas",
            answer: "a"
    },
    {
            question: "A frase icônica: 'You bow to no one my friends', foi dito por qual personagem?",
            a: "Obi-Wan Kenobi",
            b: "Gandalf",
            c: "Tex Willer",
            d: "Aragorn",
            e: "Capitāo America",
            f: "Spock",
            g: "Nenhuma das opções acima",
            answer: "d"
    }]

    let code = '';
    questions.forEach(function(v, i) {
        code += '<div data-q="'+i+'">'
        code += '<h4>'+v.question+'</h4>'
        code += ((questions[i].hasOwnProperty('a')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="a">' +v.a + '<p>' : '');
        code += ((questions[i].hasOwnProperty('b')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="b">' +v.b + '<p>' : '');
        code += ((questions[i].hasOwnProperty('c')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="c">' +v.c + '<p>' : '');
        code += ((questions[i].hasOwnProperty('d')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="d">' +v.d + '<p>' : '');
        code += ((questions[i].hasOwnProperty('e')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="e">' +v.e + '<p>' : '');
        code += ((questions[i].hasOwnProperty('f')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="f">' +v.f + '<p>' : '');
        code += ((questions[i].hasOwnProperty('g')) ? '<p><input class="quest" name="quest-'+i+'" type="radio" value="g">' +v.g + '<p>' : '');
        code += '</div>';
    })

let result = document.getElementById("result");
result.innerHTML = code;
<div id="result"></div>

  • Awesome, did not know JQUERY, I will study it to understand how your code is working, you have some literature suggestion?

  • https://www.w3schools.com/jquery/

  • https://jquery.com/

  • 6

    @Pirategull, Rodrigo’s solution was useful to you. But I wouldn’t advise focusing too much on jQuery, since it stopped receiving updates and will soon be kind of "obsolete", leaving only legacy systems with jQuery. I advise you to study this response from him and focus on Javascript Vanilla. Try to pass this response from jQuery to Javascript Vanilla. It’s just my opinion. I advise to do a better search on jQuery today in the market.

  • 1

    Thanks for the information, I assumed the correct way was by using this library, so there is a way to do this in pure javascript?

  • 3

    If jQuery is done in Javascript, yes, of course it can be done with pure Javascript. There is years old, when the web was still in its "first steps", jQuery was justifiable to circumvent the lack of compatibility between the browsers. Today, as @Gatodeschrödinger mentioned, it is no longer so necessary. Javascript and browsers have been properly standardized. There is no "right" or "wrong", but if you really want to learn Javascript (which is one of the three pillars of the front end), you should not go by jQuery, but by "pure" JS. It was bad enough, but today, undoubtedly better.

  • 1

    I’ve made the editing for pure javascript.

  • Ball show, @Rodrigozem.

  • 1

    I started learning by jQuery and there came a time when I became completely dependent on jQuery to the point where I could not do the same thing I did in jQuery in "Pure" JS. Therefore, I point out to those who are starting to start with JS vanilla. So that later, I do not go through what I went through. Not that I don’t have to study jQuery, but it’s just so I don’t have to be dependent.

  • 1

    To help in the transition jQuery -> pure JS: http://youmightnotneedjquery.com/

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.