-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
851 lines (751 loc) · 30.2 KB
/
index.html
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
<!DOCTYPE html>
<html>
<title>js-lessons</title>
<meta charset="utf-8">
<!-- Theses are just icons config - created with realfavicongenerator.net -->
<link rel="apple-touch-icon" sizes="57x57" href="assets/images/icons/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="assets/images/icons/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="assets/images/icons/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="assets/images/icons/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="assets/images/icons/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="assets/images/icons/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="assets/images/icons/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="assets/images/icons/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/images/icons/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="assets/images/icons/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="assets/images/icons/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="assets/images/icons/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="assets/images/icons/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="assets/images/icons/manifest.json">
<link rel="mask-icon" href="assets/images/icons/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="assets/images/icons/favicon.ico">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="msapplication-TileImage" content="assets/images/icons/mstile-144x144.png">
<meta name="msapplication-config" content="assets/images/icons/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<!-- These are just code mirror templates for editor -->
<link rel="stylesheet" href="assets/codemirror/theme/3024-day.css">
<link rel="stylesheet" href="assets/codemirror/theme/3024-night.css">
<link rel="stylesheet" href="assets/codemirror/theme/abcdef.css">
<link rel="stylesheet" href="assets/codemirror/theme/ambiance.css">
<link rel="stylesheet" href="assets/codemirror/theme/base16-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/bespin.css">
<link rel="stylesheet" href="assets/codemirror/theme/base16-light.css">
<link rel="stylesheet" href="assets/codemirror/theme/blackboard.css">
<link rel="stylesheet" href="assets/codemirror/theme/cobalt.css">
<link rel="stylesheet" href="assets/codemirror/theme/colorforth.css">
<link rel="stylesheet" href="assets/codemirror/theme/dracula.css">
<link rel="stylesheet" href="assets/codemirror/theme/eclipse.css">
<link rel="stylesheet" href="assets/codemirror/theme/elegant.css">
<link rel="stylesheet" href="assets/codemirror/theme/erlang-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/hopscotch.css">
<link rel="stylesheet" href="assets/codemirror/theme/icecoder.css">
<link rel="stylesheet" href="assets/codemirror/theme/isotope.css">
<link rel="stylesheet" href="assets/codemirror/theme/lesser-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/liquibyte.css">
<link rel="stylesheet" href="assets/codemirror/theme/material.css">
<link rel="stylesheet" href="assets/codemirror/theme/mbo.css">
<link rel="stylesheet" href="assets/codemirror/theme/mdn-like.css">
<link rel="stylesheet" href="assets/codemirror/theme/midnight.css">
<link rel="stylesheet" href="assets/codemirror/theme/monokai.css">
<link rel="stylesheet" href="assets/codemirror/theme/neat.css">
<link rel="stylesheet" href="assets/codemirror/theme/neo.css">
<link rel="stylesheet" href="assets/codemirror/theme/night.css">
<link rel="stylesheet" href="assets/codemirror/theme/paraiso-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/paraiso-light.css">
<link rel="stylesheet" href="assets/codemirror/theme/pastel-on-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/railscasts.css">
<link rel="stylesheet" href="assets/codemirror/theme/rubyblue.css">
<link rel="stylesheet" href="assets/codemirror/theme/seti.css">
<link rel="stylesheet" href="assets/codemirror/theme/solarized.css">
<link rel="stylesheet" href="assets/codemirror/theme/the-matrix.css">
<link rel="stylesheet" href="assets/codemirror/theme/tomorrow-night-bright.css">
<link rel="stylesheet" href="assets/codemirror/theme/tomorrow-night-eighties.css">
<link rel="stylesheet" href="assets/codemirror/theme/ttcn.css">
<link rel="stylesheet" href="assets/codemirror/theme/twilight.css">
<link rel="stylesheet" href="assets/codemirror/theme/vibrant-ink.css">
<link rel="stylesheet" href="assets/codemirror/theme/xq-dark.css">
<link rel="stylesheet" href="assets/codemirror/theme/xq-light.css">
<link rel="stylesheet" href="assets/codemirror/theme/yeti.css">
<link rel="stylesheet" href="assets/codemirror/theme/zenburn.css">
<!-- You can remove or leave at is -->
<!-- Stylesheets system - please don't remove :) -->
<link rel="stylesheet" href="assets/main.css">
<link rel="stylesheet" href="assets/codemirror/codemirror.css">
<link rel="stylesheet" href="assets/codemirror/addons/show-hint.css">
<link rel="stylesheet" href="assets/codemirror/addons/lint.css">
<link rel="stylesheet" href="assets/codemirror/addons/fullscreen.css">
<script type="text/javascript">
// Adds the implementation for Array.prototype.concatAll()
function defineConcatAll() {
Array.prototype.concatAll = function () {
var results = [];
this.forEach(function(subArray) {
results.push.apply(results, subArray);
});
return results;
};
}
/**
* Add the implementation for Array.prototype.concatMap()
*/
function defineConcatMap() {
Array.prototype.concatMap = function(fnc) {
return this.
map(function (e) {
return fnc(e);
}).
// apply the concatAll function to flatten the two-dimensional array
concatAll();
};
}
/**
* This function will be executed at the begining of each verifier function
*/
function preVerifierHook() {
// Add helpers to prevent 'undefined is not a function' like errors
defineConcatAll();
defineConcatMap();
}
function showLessonErrorMessage(exp, got, note, div){
var preTag;
var expected = JSON.stringify(JSON.parse(exp), undefined, 4);
div.innerHTML = "<h4>Expected:</h4>";
preTag = document.createElement("pre");
preTag.innerHTML += expected;
div.appendChild(preTag);
div.innerHTML += "<h4>Got:</h4>";
preTag = document.createElement("pre");
preTag.innerHTML += got;
div.appendChild(preTag);
div.innerHTML += (note !== "") ? ("<h4>Note</h4><p style=\"margin-left: 25px;\">" + note + "</p>") : "";
div.className = "info";
}
</script>
<xmp theme="united" style="display:none;">
<div id="loader-wrapper">
<div id="loader"></div>
<div class="loader-section section-left"></div>
<div class="loader-section section-right"></div>
</div>
# Welcome to js-lessons
### Interactive js exercises
---
## Preface
js-lessons is a framework of interactive exercises written in JS, for running in any (or at least in the new ones)
browser. If you wanna make a new set of exercises just make a fork of the repository stored in [js-lessons](https://github.com/jefersonla/js-lessons) and create your own JS set of exercises.
js-lessons is based on [learnrx](http://reactivex.io/learnrx/) functional programing exercise, available in
[learnrx-repo](http://reactivex.io/learnrx/), it uses [underscore](http://underscorejs.org/) to make it eficient, and
is compatible with markdown and jekyll too. Ahh we use [my-json](http://myjson.com/) to store exercises too, but you can
remove this part if you don't want to.
### Finishing the Interactive Exercises
js-lessons is not just a "tutorial", is much more than that, js-lessons is a **series of interactive exercises that you
can fill out right in your browser!** dude! It's awesome just edit the code according to the question and hit "Run",
if the code is working you can proceed to the next question, if don't the error will appear and you just need to
correct and hit go again, until the code works, nice uh!?
** Note 1: ** Use "F4" key to toggle full screen mode in editor, and press "ESC" or "F4" to leave this mode;
** Note 2: ** You can use "CTRL + SPACE" to active autocomplete;
** Note 3: ** Every "console.log()", below each question will appear in output div;
** Note 4: ** We use jshint to check the syntax of your code, but you can disable this too;
** Note 5: ** You can choose the template of the page and the editors. We have a beta version too
[js-lessons.BETA](beta.html), with a beta version of strapdown, which is not recomended.
** ! This exercise is just for test purpose, and documentation, so don't use it for real learning. **
### Personal Configurations
<p style="margin-bottom:0;"> <b> Select a theme for CodeMirror editors </b><br>
<select style="margin-top: 5px;" onchange="selectTheme()" id="select">
<option selected="">default</option>
<option>3024-day</option>
<option>3024-night</option>
<option>abcdef</option>
<option>ambiance</option>
<option>base16-dark</option>
<option>base16-light</option>
<option>bespin</option>
<option>blackboard</option>
<option>cobalt</option>
<option>colorforth</option>
<option>dracula</option>
<option>eclipse</option>
<option>elegant</option>
<option>erlang-dark</option>
<option>hopscotch</option>
<option>icecoder</option>
<option>isotope</option>
<option>lesser-dark</option>
<option>liquibyte</option>
<option>material</option>
<option>mbo</option>
<option>mdn-like</option>
<option>midnight</option>
<option>monokai</option>
<option>neat</option>
<option>neo</option>
<option>night</option>
<option>paraiso-dark</option>
<option>paraiso-light</option>
<option>pastel-on-dark</option>
<option>railscasts</option>
<option>rubyblue</option>
<option>seti</option>
<option>solarized dark</option>
<option>solarized light</option>
<option>the-matrix</option>
<option>tomorrow-night-bright</option>
<option>tomorrow-night-eighties</option>
<option>ttcn</option>
<option>twilight</option>
<option>vibrant-ink</option>
<option>xq-dark</option>
<option>xq-light</option>
<option>yeti</option>
<option>zenburn</option>
</select>
</p><p style="margin-bottom:0;"> <b> Select a theme for this page </b><br>
<select style="margin-top: 5px;" onchange="selectThemePage(this)" id="selectpage">
<option selected="">united</option>
<option>amelia</option>
<option>cerulean</option>
<option>cyborg</option>
<option>journal</option>
<option>readable</option>
<option>simplex</option>
<option>slate</option>
<option>spacelab</option>
<option>spruce</option>
<option>superhero</option>
</select>
</p><form id="login">
<label> <b> Username </b> </label> <input type="text" name="fname"> <br>
<label> <b> Password </b> </label> <input type="password" name="fpass"> <br>
</form>
<button class="go" id="loginButton" onclick="">Login</button>
## Introduction
The Array is Javascript's only collection type. Arrays are everywhere. We're going to add the five functions to the Array type, and in the process make it much more powerful and useful. As a matter of fact, Array already has the map, filter, and reduce functions! However we're going to reimplement these functions as a learning exercise.
This section will follow a pattern. First we'll solve problems the way you probably learned in school, or on your own by reading other people's code. In other words, we'll transform collections into new collections using loops and statements. Then we'll implement one of the five functions, and then use it to solve the same problem again *without* the loop. Once we've learned the five functions, you'll learn how to combine them to solve complex problems with very little code. The first two exercises have been completed in advance, but please look them over carefully!
## Chapter 1 - Traversing an Array
### Exercise 1
#### Print all the names in an array
<div class="lesson">
<textarea class="code" rows="8" cols="80">
/*jshint esversion: 6 */
function(console) { // jshint ignore:line
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"],
counter;
for(counter = 0; counter < names.length; counter++) {
console.log(names[counter]);
}
}
</textarea>
<div class="output"></div>
<div class="output"></div>
<pre id="" class="verifier">
// Traverse array with for loop
function(str, info) {
preVerifierHook();
var fun = eval("(" + str + ")");
var items = [];
var got;
var expected = '["Ben","Brian","Jafar","Matt","Priya"]';
fun({
log:function(name) {
items.push(name);
console.log(name);
}
});
got = JSON.stringify(items.sort());
if(got === expected) {
return "Success!"
}
else {
showLessonErrorMessage(expected, JSON.stringify(items.sort(), undefined, 4), 'Order does not matter', info);
}
}
</pre>
<div class="output">
<h4> Debug Console </h4> <hr>
<div class="saida">
<!-- Output -->
<pre><code></code></pre>
</div>
<div class="command-line">
<span class="console-arrow"></span>
<textarea class="console-command-line" rows="1" data-min-rows="1"></textarea>
</div>
</div>
<button class="go">Run</button>
<button class="showDebug">Show Debug</button>
</div>
<!-- ********************** START OF EXERCISE ********************** -->
<div style="display:none;" id="START-EXERCISE"></div>
<!-- ********************** LESSON 1 - BEGIN *********************** -->
<div style="display:none;" id="lessonB1"></div>
### Exercise 2
#### Use forEach to print all the names in an array
Let's repeat the previous exercise using the forEach function.
<div class="lesson">
<textarea class="code" rows="8" cols="80">
/*jshint esversion: 6 */
function(console) { // jshint ignore:line
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"];
_.forEach(names, (el) => (console.log(el)));
}
</textarea>
<div class="output"></div>
<div class="output"></div>
<pre id="" class="verifier">
// Traverse array with for loop
function(str, info) {
preVerifierHook();
var fun = eval("(" + str + ")");
var items = [];
var got;
var expected = '["Ben","Brian","Jafar","Matt","Priya"]';
fun({
log:function(name) {
items.push(name);
console.log(name);
}
});
got = JSON.stringify(items.sort());
if(got === expected) {
return "Success!"
}
else {
showLessonErrorMessage(expected, JSON.stringify(items.sort(), undefined, 4), 'Order does not matter', info);
}
}
</pre>
<div class="output">
<h4> Debug Console </h4> <hr>
<div class="saida">
<!-- Output -->
<pre><code></code></pre>
</div>
<div class="command-line">
<span class="console-arrow"></span>
<textarea class="console-command-line" rows="1" data-min-rows="1"></textarea>
</div>
</div>
<button class="go">Run</button>
<button class="showDebug">Show Debug</button>
</div>
<div style="display:none;" id="lessonE1"></div>
<!-- *********************** LESSON 1 - END *********************** -->
<!-- ********************** LESSON 2 - BEGIN ********************** -->
<div style="display:none;" id="lessonB2"></div>
## Chapter 2 - Projecting Arrays
### Exercise 3
#### Project an array of videos into an array of {id,title} pairs using forEach()
Applying a function to a value and creating a new value is called a projection. To project one array into another, we apply a projection function to each item in the array and collect the results in a new array.
For each video, add a projected {id, title} pair to the videoAndTitlePairs array.
<div class="lesson">
<textarea class="code" rows="60" cols="80">
/*jshint esversion: 6 */
function() { // jshint ignore:line
var newReleases = [
{
"id": 70111470,
"title": "Die Hard",
"boxart": "http://cdn-0.nflximg.com/images/2891/DieHard.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []
},
{
"id": 654356453,
"title": "Bad Boys",
"boxart": "http://cdn-0.nflximg.com/images/2891/BadBoys.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": [{ id:432534, time:65876586 }]
},
{
"id": 65432445,
"title": "The Chamber",
"boxart": "http://cdn-0.nflximg.com/images/2891/TheChamber.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [4.0],
"bookmark": []
},
{
"id": 675465,
"title": "Fracture",
"boxart": "http://cdn-0.nflximg.com/images/2891/Fracture.jpg",
"uri": "http://api.netflix.com/catalog/titles/movies/70111470",
"rating": [5.0],
"bookmark": [{ id:432534, time:65876586 }]
}
],
videoAndTitlePairs = [];
// ------------ INSERT CODE HERE! -----------------------------------
// Use forEach function to accumulate {id, title} pairs from each video.
// Put the results into the videoAndTitlePairs array using the Array's
// push() method. Example: videoAndTitlePairs.push(newItem);
// ------------ INSERT CODE HERE! -----------------------------------
return videoAndTitlePairs;
}
</textarea>
<div class="output"></div>
<div class="output"></div>
<pre class="verifier">
// Projection with with forEach
function(str, info) {
preVerifierHook();
var fun = eval("(" + str + ")"),
videoAndTitlePairs = fun(),
expected = '[{\"id\":675465,\"title\":\"Fracture\"},{\"id\":65432445,\"title\":\"The Chamber\"},{\"id\":70111470,\"title\":\"Die Hard\"},{\"id\":654356453,\"title\":\"Bad Boys\"}]';
// Sorting by video id
videoAndTitlePairs = _.sortBy(videoAndTitlePairs, function(video) { return video.id });
if (JSON.stringify(videoAndTitlePairs) === expected) {
return "YUPPPEEEE!";
}
else {
showLessonErrorMessage(expected, JSON.stringify(videoAndTitlePairs, undefined, 4), "", info);
}
}
</pre>
<div class="output">
<h4> Debug Console </h4> <hr>
<div class="saida">
<!-- Output -->
<pre><code></code></pre>
</div>
<div class="command-line">
<span class="console-arrow"></span>
<textarea class="console-command-line" rows="1" data-min-rows="1"></textarea>
</div>
</div>
<button class="go">Run</button>
<button class="showDebug">Show Debug</button>
</div>
<div style="display:none;" id="lessonE2"></div>
<!-- *********************** LESSON 2 - END *********************** -->
<!-- ********************** LESSON 1 - BEGIN *********************** -->
<div style="display:none;" id="lessonB3"></div>
## The end!
### Congratulations!!! :D
I hope you enjoyed use js-lessons as I enjoyed programming it!
Created By ** Jeferson Lima ** * a fan of penguins *.
</div>
<div style="display:none;" id="lessonE3"></div>
<!-- *********************** LESSON 1 - END *********************** -->
<div style="display:none;" id="END-EXERCISE"></div>
<!-- ********************** END OF EXERCISE *********************** -->
</xmp>
<!-- Nice librarie for functional programming -->
<script type="text/javascript" src="assets/underscore/underscore-min.js"></script>
<!-- Libraries for interface -->
<script src="assets/strapdown/v/0.2/strapdown.js"></script>
<script src="assets/codemirror/codemirror.js"></script>
<!-- Some code mirrors addons -->
<script src="assets/codemirror/javascript.js"></script>
<script src="assets/codemirror/addons/matchbrackets.js"></script>
<script src="assets/codemirror/addons/autorefresh.js"></script>
<script src="assets/codemirror/addons/javascript-hint.js"></script>
<script src="assets/codemirror/addons/jshint.js"></script>
<script src="assets/codemirror/addons/javascript-lint.js"></script>
<script src="assets/codemirror/addons/lint.js"></script>
<script src="assets/codemirror/addons/show-hint.js"></script>
<script src="assets/codemirror/addons/fullscreen.js"></script>
<script src="assets/codemirror/addons/active-line.js"></script>
<!-- APP LIBRARIES -->
<script src="assets/app/wordlist.js"></script>
<script src="assets/app/xhr_atomic.js"></script>
<!-- <script src="assets/app/utils.js"></script> -->
<!-- <script src="assets/app/main.js"></script> -->
<script type="text/javascript">
// Hide the remain exercises without remove markdown support
// Remember to use functional paradigm :p
(function (){
var x = document.getElementById("START-EXERCISE");
while(x.nextElementSibling.id != "END-EXERCISE"){
x.style.display = "none";
x = x.nextElementSibling;
}
// Since text area only have javascript code, is not necessary left "<a href="">"
// , or "<em>"
x = document.getElementsByClassName("code");
_.each(x, el => {
el.value = el.value.replace(/(<a\ href=").*(">)/g, "");
el.value = el.value.replace(new RegExp("</a>", 'g'), "");
el.value = el.value.replace(new RegExp("<em>", 'g'), "*");
el.value = el.value.replace(new RegExp("</em>", 'g'), "*");
});
})();
// Remove scripts not loaded, and try to reload all of them
(function (){
var x = document.getElementById("content");
var s = x.getElementsByTagName("script");
_.each(s, (el) => {
// Capture the parent element
var b = el.parentElement;
// Create a new script element
var n = document.createElement("script");
// Add attributes from the previous child, remove from the parrent and
// add the new one
b.removeChild(el);
n.async = true;
n.src = el.src + "?pikachu";
b.appendChild(n);
});
})();
var codeMirrorEditors = [];
var lessons = document.getElementsByClassName("lesson");
function scrollTo(element, to, duration) {
var difference = (to + 60) - element.scrollTop;
var perTickSize = (difference / duration).toFixed();
var perTickTime = (duration / difference).toFixed(2);
var pageHeight = window.innerHeight;
console.log("St = " + perTickSize + " | Ts = " + perTickTime + " | S = " + difference + " | D = " + duration);
var scrollingId = setInterval( _ => {
if((duration <= 0) || ((pageHeight + element.scrollTop) > element.offsetHeight)){
clearInterval(scrollingId);
return;
}
console.log(element.scrollTop);
duration -= perTickTime;
element.scrollTop = element.scrollTop + perTickSize;
}, perTickTime);
}
_.each(lessons, function (el){
var code = el.children[0];
var output = el.children[1];
var info = el.children[2];
var verifierScript = el.children[3].textContent;
var debugDiv = el.children[4];
var go = el.children[5];
var showDebug = el.children[6];
code.style.visibility = null;
code.style.display = null;
var codeDebug = debugDiv.children[2].children[0].children[0];
codeDebug.classList.add("lang-lang-javascript");
codeDebug.classList.add("prettyprint");
console.log(debugDiv);
debugDiv.children[3].onkeydown = ((ev) => {
if(ev.keyCode == 13){
var valor = ev.target.value;
ev.target.value = "";
console.log(valor);
var saida, className;
try{
saida = eval(valor);
//className = typeof saida === 'string' ? "console-info" : "console-debug";
className = "console-info";
}
catch (ex){
if (ex !== null && typeof ex !== "undefined") {
saida = ex;
} else{
saida = "An unknown error occurred!";
}
className = "console-error";
}
var s = (typeof saida === 'string') ?
saida :
((className === "console-error") ?
saida :
JSON.stringify(saida, 2, 2)),
span = document.createElement('span'),
text = document.createTextNode(s + '\n'),
span2 = document.createElement('span'),
text2 = document.createTextNode(valor + '\n');
span2.setAttribute('class', "console-log");
span2.appendChild(text2);
span.setAttribute('class', className);
span.appendChild(text);
codeDebug.appendChild(span2);
codeDebug.appendChild(span);
codeDebug.parentElement.scrollTop =
codeDebug.parentElement.scrollHeight - codeDebug.parentElement.clientHeight;
return false;
}});
CodeMirror.defaults.lint = true;
var codeMirror = CodeMirror.fromTextArea(code, {
lineNumbers: true,
mode: "javascript",
gutters: ["CodeMirror-lint-markers"],
lint: true,
matchBrackets: true,
autoRefresh: true,
tabSize: 4,
//styleActiveLine: true,
indentWithTabs: false,
hint: true,
extraKeys: {
"F4": function(cm) {
cm.setOption("fullScreen", !cm.getOption("fullScreen"));
},
"Esc": function(cm) {
if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
},
"Ctrl-Space": "autocomplete"
}
});
codeMirrorEditors.push(codeMirror);
configureReadOnlyLines(codeMirror);
go.onclick = (ev) => {
console.log("EVENT OK!");
console.log(ev);
try{
var verificador = eval("(" + verifierScript + ")");
output.textContent = verificador(codeMirror.getValue(), info, el);
} catch (ex) {
alert(ex);
}
if((output.textContent !== "Success!") && (output.textContent !== "YUPPPEEEE!")){
output.className = "error";
output.textContent = "Error!";
return;
}
output.className = "success";
info.className = "output";
var p = ev.target.parentElement.nextElementSibling;
while(!p.id.startsWith("lessonB")){
p = p.nextElementSibling;
}
p = p.nextElementSibling;
while(!p.id.startsWith("lessonE")){
p.style.display = "";
p = p.nextElementSibling;
}
//scrollTo(document.body, output.offsetTop, 600);
};
showDebug.onclick = (ev) => {
console.log(debugDiv.className);
ev.target.innerHTML = debugDiv.className == "output" ? "Hide Console" : "Show Debug";
debugDiv.className = debugDiv.className == "output" ? "console-log" : "output";
};
});
var input = document.getElementById("select");
function selectTheme() {
var theme = input.options[input.selectedIndex].textContent;
_.each(codeMirrorEditors, el => {
el.setOption("theme", theme)
});
location.hash = "#" + theme;
}
var choice = (location.hash && location.hash.slice(1)) ||
(document.location.search &&
decodeURIComponent(document.location.search.slice(1)));
if (choice) {
input.value = choice;
_.each(codeMirrorEditors, el => {
el.setOption("theme", choice)
});
}
CodeMirror.on(window, "hashchange", function() {
var theme = location.hash.slice(1);
if (theme) {
input.value = theme;
selectTheme();
}
});
// After all page got rendered remove loader
document.body.classList.add("loaded");
document.styleSheets[49].ownerNode.id = "pagetheme";
/**
* This function assumes that lines containing three consecutive
* slahes (---) are markers to delimit read-only text.
* If a marker exists, then all lines not between consecutive markers
* become read-only.
* Example:
* <textarea>
* This line is read-only
* ---
* This line is read-write
* ---
* This line is also read-only
* </textarea>
*/
function configureReadOnlyLines(codeMirrorEditor) {
var i,
doc = codeMirrorEditor.doc,
lines = doc.children[0].lines.map(line => line.text);
separatorIndices = _.range(lines.length).filter(idx => lines[idx].indexOf("---") != -1);
if (separatorIndices.length > 0) {
separatorIndices = [0].concat(separatorIndices, lines.length - 1);
for (i = 0; i < separatorIndices.length - 1; i += 2) {
doc.markText({line: separatorIndices[i], ch: 0},
{line: separatorIndices[i + 1] + 1, ch: 0},
{readOnly: true, css: "opacity: 0.6"});
}
}
}
// Allow change theme page
function selectThemePage(element){
var sheet = document.getElementById("pagetheme");
refname = sheet.href;
document.body.classList.remove("loaded");
sheet.href = refname.replace(/\/themes\/.*/g, "/themes/" + element.value + ".min.css");
setTimeout(_ => {document.body.classList.add("loaded")}, 350);
}
var myDebug = (function() {
var following = false,
pre = document.createElement('pre'),
code = document.createElement('code');
pre.appendChild(code);
//document.body.appendChild(pre);
return {
clear: clear,
follow: follow,
log: print.bind(this, 'debug'),
info: print.bind(this, 'info'),
warn: print.bind(this, 'warn'),
error: print.bind(this, 'error')
};
function clear() {
while (code.hasChildNodes()) {
code.removeChild(code.lastChild);
}
}
function follow() {
following = true;
}
function print(className, object) {
var s = (typeof object === 'string') ? object : JSON.stringify(object),
span = document.createElement('span'),
text = document.createTextNode(s + '\n');
span.setAttribute('class', className);
span.appendChild(text);
code.appendChild(span);
if (following) {
scrollToBottom();
}
}
function scrollToBottom() {
window.scrollTo(0, document.body.scrollHeight);
}
}());
/**
* This function allow save progress on dontpad.com, which is not exactly secure, but works
* pretty well. They work saving answered questions in two uri, the first URI represent a
* database with all answered questions, and the second is a hash with a backup of the entries
* in the first database:
* Example
* > dontpad.com/MATA56/id/{:hash(user, salt)} - Database with individual forms by id
* > dontpad.com/{:hash(user, pass, salt)} - Backup entry
* We recommend that you save your progress and upload to an online storage like dropbox, google
* or skydrive, because dontpad.com is not safe and we can't ensure that your data is really
* secure. Now use this only to save your progress, and create a form to send all the answers or
* maybe just the desired ones, it will be much faster and secure than this solution.
*/
function saveProgressDontpad(){
}
/**
* Instantiate the object "login" and start save progress
*/
function loginDontpad(){
}
/**
* Send answers to a google form
*/
function sendAnswers(){
}
</script>
<!-- <script src="assets/app/surprise.js"></script> -->
</html>
<!-- TODO
+ Remember to use jekyll, I think it's a good idea for clean the code
+ USE http://myjson.com/api to store JSON with progress of each student
+ USE https://ihatetomatoes.net/create-custom-preloading-screen/ while markdown is parsed and content are hidding
-->