I'm trying to realize simple testing application. And I ran into a problem. I have two arrays. The first is an array with the initial questions, the second array is the answers of users. And now I need to count the number of correct answers. I wrote the following code. I wonder: how optimal is it and, if it's bad, how to optimize it? I tried to change the "filter" to "find", but this did not affect the execution time of the code.
const questions = [
{
questionId: 1,
question: 'question?',
answers: [
{ value: '1', right: true },
{ value: '2', right: false },
{ value: '3', right: false },
{ value: '4', right: false },
],
},
{
questionId: 2,
question: 'question?',
answers: [
{ value: '1', right: false },
{ value: '2', right: false },
{ value: '3', right: false },
{ value: '4', right: true },
],
},
{
questionId: 3,
question: 'question?',
answers: [
{ value: '1', right: false },
{ value: '2', right: true },
{ value: '3', right: false },
{ value: '4', right: false },
],
},
{
questionId: 4,
question: 'question?',
answers: [
{ value: '1', right: true },
{ value: '2', right: false },
{ value: '3', right: false },
{ value: '4', right: false },
],
},
{
questionId: 5,
question: 'question?',
answers: [
{ value: '1', right: false },
{ value: '2', right: false },
{ value: '3', right: true },
{ value: '4', right: false },
],
},
]
const answersFromUser = [
{
questionId: 1,
value: '1',
},
{
questionId: 2,
value: '1',
},
{
questionId: 3,
value: '1',
},
{
questionId: 4,
value: '1',
},
{
questionId: 5,
value: '1',
},
]
const createObj = (questionId, value, right) => {
return { questionId, value, right }
}
const checkAnswers = (questionsArr, answersArr) => {
return answersArr.map(answer => {
const currentQuestion = questionsArr.filter(
question => question.questionId === answer.questionId
)
const currentAnswer = currentQuestion[0].answers.filter(
answerInCurrentQuestion => answerInCurrentQuestion.value === answer.value
)[0]
return createObj(
answer.questionId,
currentAnswer.value,
currentAnswer.right
)
})
}
const countRightAnswers = answers => {
return answers.filter(answer => answer.right).length
}
const countWrongAnswers = answers => {
return answers.filter(answer => !answer.right).length
}
console.log(checkAnswers(questions, answersFromUser))
console.log("Right Answers " + countRightAnswers(checkAnswers(questions, answersFromUser)))
console.log("Wrong Answers " + countWrongAnswers(checkAnswers(questions, answersFromUser)))