-
Notifications
You must be signed in to change notification settings - Fork 12
/
machine.js
107 lines (104 loc) · 2.51 KB
/
machine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import {assign, Machine} from 'xstate'
import {fetchAndNormalizeQuizData} from './utils'
const machine = Machine(
{
id: 'Machine',
initial: 'welcome',
context: {
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
},
states: {
welcome: {
on: {
START_QUIZ: 'loading',
},
},
loading: {
invoke: {
id: 'getQuizData',
src: 'fetchAndNormalizeQuizData',
onDone: {
target: 'quiz',
actions: assign({
questions: (_, event) => event.data,
}),
},
onError: {
target: 'failure',
},
},
},
failure: {
on: {
RETRY: 'loading',
START_OVER: 'welcome',
},
},
quiz: {
on: {
'': {
target: 'results',
actions: [],
cond: 'allQuestionsAnswered',
},
ANSWER_FALSE: {
actions: 'updateAnswer',
},
ANSWER_TRUE: {
actions: 'updateAnswer',
},
},
},
results: {
on: {
PLAY_AGAIN: 'welcome',
},
exit: 'resetGame',
},
},
},
{
actions: {
resetGame: assign({
currentQuestion: 0,
currentQuestionDisplay: 1,
questions: [],
totalCorrectAnswers: 0,
}),
updateAnswer: assign((ctx, event) => ({
questions: [
...ctx.questions.slice(0, ctx.currentQuestion),
{
...ctx.questions[ctx.currentQuestion],
userAnswer: event.answer,
correct:
ctx.questions[ctx.currentQuestion].correctAnswer === event.answer,
},
...ctx.questions.slice(ctx.currentQuestion + 1),
],
totalCorrectAnswers:
ctx.questions[ctx.currentQuestion].correctAnswer === event.answer
? (ctx.totalCorrectAnswers += 1)
: ctx.totalCorrectAnswers,
currentQuestion: ctx.currentQuestion += 1,
currentQuestionDisplay: ctx.currentQuestionDisplay += 1,
})),
},
guards: {
allQuestionsAnswered: ctx => {
return (
ctx.questions.filter(
(question) => question.correct !== undefined,
).length === ctx.questions.length && true
)
},
},
services: {
fetchAndNormalizeQuizData: () => fetchAndNormalizeQuizData(),
},
},
)
export default machine