Untitled

mail@pastecode.io avatar
unknown
plain_text
6 months ago
1.9 kB
1
Indexable
Never
import {useState} from "react";
import QuestionList from "./data/questions.json";
import QuizResult from "./QuizResult.js";
import Question from "./Question.js";

function calculateResult(markedAnswers) {
    let correct = 0;
    QuestionList.forEach((question, index) => {
        if(question.correctOptionIndex == markedAnswers[index]) {
            correct++;
        }
    });
    return {
        total:QuestionList.length,
        correct: correct,
        percentage: Math.trunc((correct / QuestionList.length) * 100)
    };
}

function QuizScreen ({retry}) {
    const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
    const [markedAnswers, setMarkedAnswers] = useState(new Array(QuestionList.length));
    const isQuestionEnd = currentQuestionIndex === QuestionList.length;

    return (
        <div className="quiz-screen">
            {
                isQuestionEnd ? (
                    <QuizResult
                    result={calculateResult(markedAnswers)}
                    retry={retry}
                    />
                ) : (
                    <Question
                        question= {QuestionList[currentQuestionIndex]}
                        totalQuestions= {QuestionList.length}
                        currentQuestion = {currentQuestionIndex + 1}
                        setAnswer={(index) => { 
                            setMarkedAnswers((arr) => {
                                let newArr = [...arr];
                                newArr[currentQuestionIndex -1 ] = index;
                                return newArr;
                            });
                            setCurrentQuestionIndex(currentQuestionIndex + 1);
                        }}
                    />
                )
                    }
                    </div>
    )
}


export default QuizScreen;
Leave a Comment