Skip to content

Commit 260633b

Browse files
committed
refactor: add helper functions for quizzes
1 parent 63be5a1 commit 260633b

File tree

2 files changed

+40
-15
lines changed

2 files changed

+40
-15
lines changed

components/mdx/Quiz.tsx

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,11 @@ import {
1212
ModalCloseButton,
1313
useToast,
1414
} from '@chakra-ui/react'
15-
import React, { FC, useEffect, useState } from 'react'
15+
import React, { FC, useState } from 'react'
16+
import {
17+
getCorrectAnswersIndexes,
18+
haveSameElements,
19+
} from '../../utils/QuizHelpers'
1620

1721
interface QuizProps {
1822
quiz: string
@@ -131,32 +135,24 @@ const Quiz: FC<QuizProps> = (props: QuizProps) => {
131135
return quizNotAnswered()
132136
}
133137

134-
let hasWrongAnswers = false
135138
let wrongAnswersCounter = 0
136139

137140
const newCorrectAnswers: number[] = []
138141

139-
quiz.questions.forEach((q, index) => {
140-
let correctAnswersIndexes = q.options
141-
.filter((option) => option.correct)
142-
.map((correctOption) => q.options.indexOf(correctOption))
142+
quiz.questions.forEach((question, index) => {
143+
let correctAnswersIndexes = getCorrectAnswersIndexes(question)
143144

144-
for (let i = 0; i < answers[index].length; i++) {
145-
if (answers[index].length >= 2)
146-
answers[index] = answers[index].sort((a, b) => a - b)
147-
if (correctAnswersIndexes[i] !== answers[index][i]) {
148-
hasWrongAnswers = true
149-
wrongAnswersCounter++
150-
return
151-
}
145+
if (!haveSameElements(answers[index], correctAnswersIndexes)) {
146+
wrongAnswersCounter++
147+
return
152148
}
153149

154150
newCorrectAnswers.push(index)
155151
})
156152

157153
setCorrectAnswers(newCorrectAnswers)
158154

159-
if (hasWrongAnswers) {
155+
if (wrongAnswersCounter >= 1) {
160156
return quizFailedToast(wrongAnswersCounter)
161157
}
162158

utils/QuizHelpers.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
interface Question {
2+
question: string
3+
options: [
4+
{
5+
answer: string
6+
correct?: boolean
7+
},
8+
]
9+
}
10+
11+
export function getCorrectAnswersIndexes(question: Question): number[] {
12+
return question.options
13+
.filter((option) => option.correct)
14+
.map((correctOption) => question.options.indexOf(correctOption))
15+
}
16+
17+
export function haveSameElements(arr1: number[], arr2: number[]): boolean {
18+
if (arr1.length !== arr2.length) {
19+
return false
20+
}
21+
let arr1Sorted = arr1.sort()
22+
let arr2Sorted = arr2.sort()
23+
for (let i = 0; i < arr1Sorted.length; i++) {
24+
if (arr1Sorted[i] !== arr2Sorted[i]) {
25+
return false
26+
}
27+
}
28+
return true
29+
}

0 commit comments

Comments
 (0)