-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
393 lines (346 loc) · 10.8 KB
/
index.js
File metadata and controls
393 lines (346 loc) · 10.8 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
(function (document, window) {
// DEPENDENCIES
// ============================================================
const probs = require('pjs-problems').es5;
const dedent = require('dedent');
const assert = require('chai').assert;
// PROBLEM TEMPLATE NICE-IFICATION
// ============================================================
function dedentStrings(problems) {
return problems.map(prob => {
prob.given = dedent(prob.given)
prob.answer = dedent(prob.answer)
return prob
});
}
// PROBLEMS
// ============================================================
let problems = [];
Object.keys(probs).forEach(subject => {
problems.push(...probs[subject]);
});
problems = dedentStrings(problems);
// CONFIG
// ============================================================
// Hoist current problem
let currentProblem;
// Keys to ignore while user is navigating around the textarea but not changing any code
const ignoreKeyCodes = [
9, // Tab
37, // Left arrow
39, // Right arrow
38, // Up arrow
40 // Down arrow
];
let config = {
shuffle: true,
timer: false,
currentIndex: 0
};
let state = {
currentProblem: getCurrentProblem(problems)
}
// HELPERS
// ============================================================
function debounce(func, wait, immediate) {
let timeout;
return function () {
const context = this;
const args = arguments;
const later = function () {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
// UI
// ============================================================
// elements
const problemEl = document.getElementById('problem');
const codeEl = document.getElementById('code');
const testSuiteEl = document.getElementById('test-suite');
const testTotalEl = document.getElementById('test-total');
const evalConsoleEl = document.getElementById('eval-output');
const assertConsoleEl = document.getElementById('assert-output');
const shuffleProblemsButtonEl = document.getElementById('shuffle-problems');
const previousProblemButtonEl = document.getElementById('prev-problem');
const nextProblemButtonEl = document.getElementById('next-problem');
// LOCALSTORE
// --------------------------------------------------------------------------------
// Pull config from localstorage
if (window.localStorage) {
const localConfig = localStorage.getItem('js_practice_config');
if (localConfig) {
try {
config = JSON.parse(localConfig);
loadApp(config);
} catch (err) {
console.log('LOCAL_CONFIG PARSE ERR:', err);
}
} else {
console.log('LOCAL_CONFIG: No local config');
loadApp(config);
}
}
function updateLocalstore(config) {
return new Promise((resolve, reject) => {
if (window.localStorage) {
localStorage.setItem('js_practice_config', JSON.stringify(config));
console.log('Saved config: ', config);
resolve();
} else {
reject();
}
});
}
// Get indexes
function getRandomIndex(problemsArr) {
const ind = Math.floor(Math.random() * problemsArr.length);
config.currentIndex = ind;
updateLocalstore(config);
return ind;
}
function getPreviousIndex(problemsArr) {
let probInd;
const currentIndex = config.currentIndex;
// If at beginning, go to end
if (currentIndex === 0) {
probInd = problemsArr.length - 1;
} else {
probInd = currentIndex - 1;
}
return probInd;
}
function getNextIndex(problemsArr) {
let probInd;
const currentIndex = config.currentIndex;
// If at end or invalid, restart series
if (currentIndex >= problemsArr.length - 1 || currentIndex < 0) {
probInd = 0;
} else {
probInd = currentIndex + 1;
}
return probInd;
}
// Get problems
function getCurrentProblem(problemsArr) {
return problemsArr[config.currentIndex];
}
function previousProblem() {
console.log('previousProblem!');
// Activate back button, for visual queue of nav feedback
previousProblemButtonEl.classList.add('active');
config.currentIndex = config.shuffle
? getRandomIndex(problems)
: getPreviousIndex(problems);
updateLocalstore(config).then(() => {
window.location.reload();
});
}
function nextProblem() {
console.log('nextProblem!');
// Activate next button, for visual queue of nav feedback
nextProblemButtonEl.classList.add('active');
config.currentIndex = config.shuffle
? getRandomIndex(problems)
: getNextIndex(problems);
updateLocalstore(config).then(() => {
window.location.reload();
});
}
function toggleShuffle() {
console.log('toggle shuffle!');
config.shuffle = !config.shuffle; // Flip it
shuffleProblemsButtonEl.classList.toggle('active');
previousProblemButtonEl.parentNode.classList.toggle('hidden');
updateLocalstore(config);
}
function loadProblem(problemObj) {
state.currentProblem = problemObj;
// Prob question
problemEl.innerText = problemObj.prompt;
// Prob given code
if (problemObj.given) {
codeEl.value = problemObj.given;
}
// Seed the tests, pass (init = true) as second param
testSuite(null, true);
}
// TODO: Build the assert errors into the test dom on each update.
function updateTests(testStatus, init) {
if (init === true) {
buildTests(state.currentProblem.tests);
}
updateTestStatus(testStatus);
}
function buildTests(tests) {
if (tests) {
const testsDom = tests
.map(test => {
return `<div class="test monospace">
<div class="test-state">[✘]</div>
<div class="test-name">${test.name}</div>
</div>`;
})
.join('');
testSuiteEl.innerHTML = testsDom;
}
}
function updateTestStatus(testStatuses) {
if (!testStatuses) {
throw new Error('No testStatuses provided.');
}
// Find out if all tests have passed or not
let allPassed = true;
testStatuses.forEach(testPassed => {
if (testPassed !== true) {
allPassed = false;
}
});
const testEls = [].slice.call(testSuiteEl.querySelectorAll('.test-state'));
testEls.forEach((testStatusEl, iter) => {
if (testStatuses[iter] === true) {
testStatusEl.innerHTML = '[✓]';
testStatusEl.classList.remove('fail');
testStatusEl.classList.add('pass');
} else {
testStatusEl.innerHTML = '[✘]';
testStatusEl.classList.remove('pass');
testStatusEl.classList.add('fail');
}
});
if (allPassed === true) {
testTotalEl.innerText = 'PASS';
testTotalEl.classList.remove('fail');
testTotalEl.classList.add('pass');
} else {
testTotalEl.innerText = 'FAIL';
testTotalEl.classList.remove('pass');
testTotalEl.classList.add('fail');
}
}
function printAssertError(errObj) {
// Make element string
let inner = '';
if (errObj !== null) {
inner = `
<div class="assert-error">
Expected: ${JSON.stringify(errObj.expected)}
Actual: ${JSON.stringify(errObj.actual)}
</div>`;
}
// Prepend element
assertConsoleEl.innerHTML = inner;
}
function printEvalOutput(errObj, output) {
// Make element string
let inner = '';
if (errObj && errObj.message !== undefined) {
inner = `
<div class="assert-error">
Syntax Error: ${JSON.stringify(errObj.message)}
</div>`;
} else if (output) {
inner = `
<div class="assert-error">
Output: ${JSON.stringify(output)}
</div>`;
}
// Prepend element
evalConsoleEl.innerHTML = inner;
}
// VERIFICATION LOGIC
// ============================================================
function testSuite(init) {
// Show 'working' indicator
testTotalEl.classList.toggle('working');
// Run stuff
const output = getOutput(codeEl.value);
// Run tests on code, return object/array of test results
const tested = runTests(output);
// Hide 'working' indicator
testTotalEl.classList.toggle('working');
// Update UI with results
updateTests(tested, init);
}
function getOutput(code) {
let evald = false;
try {
evald = eval(`(function(){${code}})()`); // eslint-disable-line no-eval
printEvalOutput(null, evald); // Print current output
} catch (err) {
printEvalOutput(err);
}
return evald;
}
function runTests(output) {
let tested = false;
tested = state.currentProblem.tests.map(test => {
let testOutcome = false;
try {
if (output) {
testOutcome = eval(test.test);
}
printAssertError(null);
} catch (err) {
printAssertError(err);
}
return testOutcome;
});
return tested;
}
// Wrapped to prevent race with local config retrieval
function loadApp(config) {
console.log('loading app!');
// Show current toggle state
if (config.shuffle === true) {
shuffleProblemsButtonEl.classList.add('active');
previousProblemButtonEl.parentNode.classList.add('hidden');
}
// Keybinding stuff
// ============================================================
// Debounced code validation
const debouncedInputValidation = debounce(e => {
// If not arrow keys or other non-character keys
if (ignoreKeyCodes.indexOf(e.keyCode) === -1) {
// Run test suite
testSuite();
}
}, 200);
function problemNav(e) {
// Go to previous problem keybinding
// If CMD/CTRL + SHIFT + RETURN/ENTER
if (config.shuffle === false && e.keyCode === 13 && e.shiftKey && (e.metaKey || e.ctrlKey)) {
// Go to next problem
previousProblem();
} else if (e.keyCode === 13 && !e.shiftKey && (e.metaKey || e.ctrlKey)) {
// Go to next problem keybinding
// If CMD/CTRL + RETURN/ENTER
// Go to next problem
nextProblem();
}
}
// Event Bindings
// ============================================================
// Bind it up
codeEl.addEventListener('keydown', debouncedInputValidation);
document.addEventListener('keydown', problemNav);
shuffleProblemsButtonEl.addEventListener('click', toggleShuffle);
previousProblemButtonEl.addEventListener('click', previousProblem);
nextProblemButtonEl.addEventListener('click', nextProblem);
// Start it up!
// Load current problem
const currProb = getCurrentProblem(problems);
loadProblem(currProb);
// Initalized test suite with starting failures
testSuite(true);
}
})(document, window);