-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.thread.js
More file actions
262 lines (229 loc) · 6.77 KB
/
worker.thread.js
File metadata and controls
262 lines (229 loc) · 6.77 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*global self*/
// DEPS
// ============================================================
import diff from 'virtual-dom/diff'
import serializePatch from 'vdom-serialized-patch/serialize'
import fromJson from 'vdom-as-json/fromJson'
import app from './views/app'
import chai from 'chai'
import utils from './utils'
// import initialProblems from './problems/initial'
import probbs from 'pjs-problems'
let currentVDom
let renderCount = 0
// merge all the problem categories for now, until we have user-driven filtering
let problems = Object.entries(probbs)
.map(item => item[1])
.reduce((curr,next) => {
return curr.concat(next);
});
// dedent the code strings in problems
problems = utils.dedentStringsInProblems(problems);
// STATE OBJECT
// ============================================================
// our entire application state
// as a plain object
let state = {
currentProblemIndex: 0, // start with first index
events: [],
problem: null, // start with first problem
shuffle: true,
testsPass: false,
url: '/',
}
// APP METHODS
// ============================================================
// PROBLEM NAVIGATION
// ============================================================
function getNextProblemIndex(currIndex, length) {
let newIndex;
// if shuffle on, return new random index
if (state.shuffle) {
newIndex = Math.floor(Math.random() * length)
} else {
// if at the end of the problems array, go to the start
if (state.currentProblemIndex === problems.length -1) {
newIndex = 0
} else {
// if not at then end, increment as normal
newIndex = state.currentProblemIndex + 1
}
}
return newIndex
}
function getNextProblem(probs) {
// set new index to state
state.currentProblemIndex = getNextProblemIndex(state.currentProblemIndex, problems.length)
// return new problem from that index
return probs[state.currentProblemIndex]
}
// TEST VALIDATION
// ============================================================
function evaluate(input = undefined) {
let output
try {
output = eval(`(function(){${input}})()`)
} catch(err) {
output = err
}
return output
}
function testSuite(input = 'undefined', problem) {
const assert = chai.assert;
const output = evaluate(input)
let testResultBooleans = []
// stringify output to show in ui console
problem.evaluated = JSON.stringify(output);
let problemWithTestFeedback = problem.tests.map(test => {
try {
const testEval = eval(test.test);
if (testEval === true) {
testResultBooleans.push(true)
}
test.testFeedback = testEval
} catch (err) {
testResultBooleans.push(false)
test.testFeedback = err
}
return test
})
// "all tests pass", set it in state
state.testsPass = testResultBooleans.every((result => result === true))
// have main thread play testpass sound when it catches the next change diff
if (state.testsPass === true) {
const soundObj = {
name: 'sound', data: {
id: 'pass'
}
};
state.events.push(soundObj)
const analyticsObj = {
name: 'ga',
data: {
hitType: 'event',
eventLabel: 'Problem',
eventCategory: state.problem.name,
eventAction: 'solved'
}
};
state.events.push(analyticsObj);
} else {
// remove success sound event
state.events = state.events.filter(item => {
return !(item.name === 'sound' && item.data.id === 'pass')
})
// remove ga event
state.events = state.events.filter(item => {
return !(item.name === 'ga' && item.data.eventAction === 'solved')
})
}
return problemWithTestFeedback
}
// EVENT BUS
// ============================================================
// messages from the main thread come
// in here
self.onmessage = ({data}) => {
const { type, payload } = data
// handle different event types
// update the state accordingly
switch (type) {
case 'start': {
currentVDom = fromJson(payload.virtualDom)
if (payload.localState) {
state.shuffle = payload.localState.shuffle
}
state.url = state.url || payload.url
// go get a new problem!
state.problem = state.shuffle
? problems[getNextProblemIndex(state.currentProblemIndex, problems.length)]
: problems[0]
state.problem.tests = testSuite(state.problem.given, state.problem)
state.events = []
const analyticsStartObj = {
name: 'ga',
data: {
hitType: 'event',
eventLabel: 'Started',
eventCategory: state.problem && state.problem.name,
eventAction: 'started_at'
}
};
state.events.push(analyticsStartObj);
break
}
case 'setUrl': {
state.url = payload
state.events = []
break
}
case 'next': {
state.problem = getNextProblem(problems)
state.testsPass = false
state.events = []
const analyticsNavObj = {
name: 'ga',
data: {
hitType: 'event',
eventLabel: 'Navigation',
eventCategory: state.problem && state.problem.name,
eventAction: 'navigated_to'
}
};
state.events.push(analyticsNavObj);
state.problem.tests = testSuite(state.problem.given, state.problem)
break
}
case 'shuffle': {
state.shuffle = !state.shuffle
state.events = []
const analyticsShuffleObj = {
name: 'ga',
data: {
hitType: 'event',
eventLabel: 'Configuration',
eventCategory: state.shuffle,
eventAction: 'shuffle_pressed'
}
};
state.events.push(analyticsShuffleObj);
break
}
case 'codeupdate': {
state.events = []
state.problem.tests = testSuite(payload, state.problem)
break
}
case 'newproblems': {
state.events = []
problems.push(...utils.dedentStringsInProblems(payload))
// todo: show a toast that new content has been loaded for them
break
}
}
// UPDATING THE DOM
// ============================================================
// just for fun
// serialize the state, and delete reversible big bits so we can save in localstorage
let tinyState = {
shuffle: state.shuffle
}
const serializedState = JSON.stringify(tinyState)
// state events to pass to main thread
const stateEvents = state.events || null;
// our entire app in one line:
const newVDom = app(state)
// do the diff
const patches = diff(currentVDom, newVDom)
// cache last vdom so we diff against
// the new one the next time through
currentVDom = newVDom
// send patches and current url back to the main thread
self.postMessage({url: state.url, payload: serializePatch(patches), serializedState, stateEvents})
}
module.exports = {
getNextProblemIndex,
getNextProblem,
evaluate,
testSuite
}