-
Notifications
You must be signed in to change notification settings - Fork 291
/
index.html
5073 lines (4493 loc) · 173 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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/codemirror/codemirror.css">
<link rel="stylesheet" href="assets/app/site.css">
<title>Functional Programming in Javascript</title>
<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();
}
</script>
</head>
<body>
<div class="content">
<div class="grab-answers">
<p>This is an interactive learning course with exercises you fill out right in the browser. <b>If you just want to browse the content click the button below</b>:</p>
<button class="green-button show-answers">Show all the answers so I can just browse.</button>
</div>
<h1 class="center">Functional Programming in Javascript</h1>
<p>This is a series of interactive exercises for learning Microsoft's Reactive Extensions (Rx) Library for Javascript.
So why is the title "Functional Programming in Javascript"? Well it turns out that the key to learning Rx is
training yourself to use functional programming to manipulate collections. Functional programming provides
developers with the tools to abstract common collection operations into reusable, composable building blocks.
You'll be surprised to learn that most of the operations you perform on collections can be accomplished with
<b>five simple functions</b> (some native to JavaScript and some included in the
<a href="https://github.com/ReactiveX/rxjs">RxJS library</a>):
</p>
<ol>
<li>map</li>
<li>filter</li>
<li>concatAll</li>
<li>reduce</li>
<li>zip</li>
</ol>
<p>Here's my promise to you: if you learn these 5 functions your code will become shorter, more self-descriptive,
and more durable. Also, for reasons that might not be obvious right now, you'll learn that these five functions
hold the key to simplifying asynchronous programming. Once you've finished this tutorial you'll also have all
the tools you need to easily avoid race conditions, propagate and handle asynchronous errors, and sequence
events and AJAX requests. In short,
<b>these 5 functions will probably be the most powerful, flexible, and useful functions you'll ever learn.</b>
</p>
<h2>Finishing the Interactive Exercises</h2>
<p>This isn't just a tutorial, it's a
<b>series of interactive exercises that you can fill out right in your browser!</b> It's easy to finish the
exercises. Just edit the code and press "Run." If the code works, a new exercise will appear below. Otherwise an
error will appear.
</p>
<p><b>Note:</b> Use the "F4" key to toggle full screen mode for each editor.</p>
<p>This tutorial may have bugs, so if you get into a weird state or you're sure you've got the right answer but
can't move on, just refresh your browser. If you're using a modern browser, and if you're here I assume you are,
the state of your exercises will be saved. If you want, you can also
<a href="javascript:localStorage.newState = ''; document.location.reload();">restart the lab.</a></p>
<p>This tutorial is on
<a href="https://github.com/ReactiveX/learnrx">GitHub</a>, and is asymptotically approaching
completion. If you'd like to add an exercise, clarify a problem description, or fix a bug feel free to
<a href="https://github.com/ReactiveX/learnrx/fork">fork</a> and send us a pull request. We'll
try and fit user-contributed exercises into a narrative.
</p>
<div class="grab-answers">
<p>Your answers will be saved in local storage. Use the buttons below if you want to transfer them to another machine:</p>
<button class="green-button get-answer">Get Answers as JSON</button>
<button class="blue-button set-answer">Set JSON Answers</button>
</div>
<h2>Working with Arrays</h2>
<p>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.</p>
<p>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
<i>without</i> 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!
</p>
<h3>Traversing an Array</h3>
<!-- ************************* LESSON ************************* -->
<div class="lesson" style="visibility: visible">
<h4>Exercise 1: Print all the names in an array</h4>
<textarea class="code" rows="8" cols="80">
function(console) {
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"],
counter;
for(counter = 0; counter < names.length; counter++) {
console.log(names[counter]);
}
}
</textarea>
<button class="go">Run</button>
<span class="aside"><- Click here to try your solution. If it works, you'll move on to the next exercise.</span>
<div class="output"></div>
<pre class="verifier">
// Traverse array with for loop
function(str) {
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, got, 'Note: order does not matter');
}
}
</pre>
<pre class="answer">
function(console) {
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"],
counter;
for(counter = 0; counter < names.length; counter++) {
console.log(names[counter]);
}
}
</pre>
<p class="post">Ask yourself this question: <b>did we need to specify the <i>order</i> in which the names were
printed?</b> If not, why do it?
</p>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 2: Use forEach to print all the names in an array</h4>
<p>Let's repeat the previous exercise using the forEach function.</p>
<textarea class="code" rows="8" cols="80">
function(console) {
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"];
names.forEach(function(name) {
console.log(name);
});
}
</textarea>
<button class="go">Run</button>
<div class="output"></div>
<pre class="verifier">
// Traverse array with foreach
function(str) {
preVerifierHook();
if (str.indexOf(".forEach") === -1) {
return "You have to use forEach!"
}
var fun = eval("(" + str + ")");
var items =[];
fun({
log:function(name) {
items.push(name);
console.log(name);
}
});
if(JSON.stringify(items.sort()) === '["Ben","Brian","Jafar","Matt","Priya"]') {
return "Success!"
}
else {
throw 'console.log did not receive all of these values: "Ben","Brian","Jafar","Matt","Priya" (note: order does not matter)'
}
}
</pre>
<pre class="answer">
function(console) {
var names = ["Ben", "Jafar", "Matt", "Priya", "Brian"];
names.forEach(function(name) {
console.log(name);
});
}
</pre>
<div class="post">
<p>
Notice that forEach lets us specify <i>what</i> we want to happen to each item in the array, but hides <i>how</i> the array is traversed.
</p>
<h3>Projecting Arrays</h3>
<p>Applying a function to a value and creating a new value is called a <i>projection</i>. 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.
</p>
</div>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 3: Project an array of videos into an array of {id,title} pairs using forEach()</h4>
<p>For each video, add a projected {id, title} pair to the videoAndTitlePairs array.</p>
<textarea class="code" rows="60" cols="80">
function() {
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>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Projection with with forEach
function(str) {
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 = videoAndTitlePairs.sortBy(function(video) { return video.id });
if (JSON.stringify(videoAndTitlePairs) === expected) {
return true;
}
else {
showLessonErrorMessage(expected, JSON.stringify(videoAndTitlePairs));
}
}
</pre>
<pre class="answer">
function() {
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 = [];
newReleases.forEach(function(video) {
videoAndTitlePairs.push({ id: video.id, title: video.title });
});
return videoAndTitlePairs;
}
</pre>
<div class="post">
<p>All array projections share two operations in common:</p>
<ol>
<li>Traverse the source array</li>
<li>Add each item's projected value to a new array</li>
</ol>
<p>Why not abstract away <i>how</i> these operations are carried out?</p>
</div>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 4: Implement map()</h4>
<p>To make projections easier, let's add a <b>map()</b> function to the Array type. Map accepts the projection
function to be applied to each item in the source array, and returns the projected array.
</p>
<textarea class="code" rows="20" cols="80">
Array.prototype.map = function(projectionFunction) {
var results = [];
this.forEach(function(itemInArray) {
// ------------ INSERT CODE HERE! ----------------------------
// Apply the projectionFunction to each item in the array and add
// each result to the results array.
// Note: you can add items to an array with the push() method.
// ------------ INSERT CODE HERE! ----------------------------
});
return results;
};
// JSON.stringify([1,2,3].map(function(x) { return x + 1; })) === '[2,3,4]'
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Implement map()
function(str) {
preVerifierHook();
var fun = eval(str),
arr = [1,2,3],
result;
result = arr.map(function(x) { return x + 1});
if (JSON.stringify(arr) !== "[1,2,3]") {
throw "Whoa! You changed the input array. Map never changes the value of the array passed in. It creates a new array with the results of applying the projection function to every value in the old array."
}
else if(JSON.stringify(result) !== '[2,3,4]') {
throw 'Expected that [1,2,3].map(function(x) { return x + 1}) would equal [2,3,4].'
}
}
</pre>
<pre class="answer">
Array.prototype.map = function(projectionFunction) {
var results = [];
this.forEach(function(itemInArray) {
results.push(projectionFunction(itemInArray));
});
return results;
};
// JSON.stringify([1,2,3].map(function(x) { return x + 1; })) === '[2,3,4]'
</pre>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 5: Use map() to project an array of videos into an array of {id,title} pairs</h4>
<p>Let's repeat the exercise of collecting {id, title} pairs for each video in the newReleases array, but <b>this
time we'll use our map function.</b>
</p>
<textarea class="code" rows="60" cols="80">
function() {
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 }]
}
];
// ------------ INSERT CODE HERE! -----------------------------------
// Use map function to accumulate {id, title} pairs from each video.
return newReleases.map // finish this expression!
// ------------ INSERT CODE HERE! -----------------------------------
}
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Projection with map
function(str) {
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 = videoAndTitlePairs.sortBy(function(video) { return video.id });
if (JSON.stringify(videoAndTitlePairs) === expected) {
return true;
}
else {
throw 'Expected: ' + expected;
}
}
</pre>
<pre class="answer">
function() {
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 }]
}
];
return newReleases.map(function(video) { return { id: video.id, title: video.title }; });
}
</pre>
<div class="post">
<p>Notice that map allows us to specify <i>what</i> projection we want to apply to an array, but hides
<i>how</i> the operation is carried out.
</p>
<h3>Filtering Arrays</h3>
<p>Like projection, filtering an array is also a very common operation. To filter an array we apply a test to each item
in the array and collect the items that pass into a new array.
</p>
</div>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 6: Use forEach() to collect only those videos with a rating of 5.0</h4>
<p>Use forEach() to loop through the videos in the newReleases array and, if a video has a rating of 5.0, add it to
the videos array.
</p>
<textarea class="code" rows="60" cols="80">
function() {
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 }]
}
],
videos = [];
// ------------ INSERT CODE HERE! -----------------------------------
// Use forEach function to accumulate every video with a rating of 5.0
// ------------ INSERT CODE HERE! -----------------------------------
return videos;
}
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Filter with forEach
function(str) {
preVerifierHook();
var fun = eval("(" + str + ")"),
videos = fun(),
expected = '[{"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,"bookmark":[{"id":432534,"time":65876586}]},{"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,"bookmark":[{"id":432534,"time":65876586}]}]';
// Sorting by video id
videos = videos.sortBy(function(v) { return v.id; });
if (JSON.stringify(videos) === expected) {
return true;
}
else {
throw 'Expected: ' + expected;
}
}
</pre>
<pre class="answer">
function() {
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 }]
}
],
videos = [];
newReleases.forEach(function(video) {
if (video.rating === 5.0) {
videos.push(video);
}
});
return videos;
}
</pre>
<div class="post">
<p>Notice that, like map(), <b>every filter() operation shares some operations in common</b>:</p>
<ol>
<li>Traverse the array</li>
<li>Add objects that pass the test to a new array</li>
</ol>
<p>Why not abstract away how these operations are carried out?</p>
</div>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h4>Exercise 7: Implement filter()</h4>
<p>To make filtering easier, let's add a filter() function to the Array type. The filter() function accepts a <i>predicate</i>.
A predicate is a function that accepts an item in the array, and returns a boolean indicating whether the item
should be retained in the new array.</p>
<textarea class="code" rows="20" cols="80">
Array.prototype.filter = function(predicateFunction) {
var results = [];
this.forEach(function(itemInArray) {
// ------------ INSERT CODE HERE! ----------------------------
// Apply the predicateFunction to each item in the array.
// If the result is truthy, add the item to the results array.
// Note: remember you can add items to the array using the array's
// push() method.
// ------------ INSERT CODE HERE! ----------------------------
});
return results;
};
// JSON.stringify([1,2,3].filter(function(x) { return x > 2})) === "[3]"
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Implement filter()
function(str) {
preVerifierHook();
var fun = eval(str),
arr = [1,2,3],
result;
result = arr.filter(function(x) { return x > 2});
if (JSON.stringify(arr) !== "[1,2,3]") {
throw "Whoa! You changed the input array. Filter never changes the value of the array passed in. It creates a new array that includes only those items in the old array that pass the predicate function."
}
else if(JSON.stringify(result) !== '[3]') {
throw 'Expected that [1,2,3].filter(function(x) { return x > 2}) would equal [3].'
}
}
</pre>
<pre class="answer">
Array.prototype.filter = function(predicateFunction) {
var results = [];
this.forEach(function(itemInArray) {
if (predicateFunction(itemInArray)) {
results.push(itemInArray);
}
});
return results;
};
// JSON.stringify([1,2,3].filter(function(x) { return x > 2})) === "[3]"
</pre>
<p class="post">Like map(), filter() lets us express <i>what</i> data we want without requiring us to specify <i>how</i>
we want to collect the data.</p>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h3>Query Data by Chaining Method Calls</h3>
<h4>Exercise 8: Chain filter and map to collect the ids of videos that have a rating of 5.0</h4>
<textarea class="code" rows="60" cols="80">
function() {
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 }]
}
];
// ------------ INSERT CODE HERE! -----------------------------------
// Chain the filter and map functions to select the id of all videos
// with a rating of 5.0.
return newReleases // Complete this expression
// ------------ INSERT CODE HERE! -----------------------------------
}
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Filter with filter()
function(str) {
preVerifierHook();
var fun = eval("(" + str + ")"),
videoids = fun(),
expected = '[675465,654356453]';
// Sorting by video id
videoids = videoids.sortBy(function(v) { return v; });
if (JSON.stringify(videoids) === expected) {
return true;
}
else {
throw 'Expected: ' + expected;
}
}
</pre>
<pre class="answer">
function() {
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 }]
}
];
return newReleases.
filter(function(video) {
return video.rating === 5.0;
}).
map(function(video) {
return video.id;
});
}
</pre>
<p class="post">Chaining together map() and filter() gives us a lot of expressive power. These high level functions
let us express <i>what</i> data we want, but leave the underlying libraries a great deal of flexibility in terms
of <i>how</i> our queries are executed.</p>
</div>
<!-- ************************* LESSON ************************* -->
<div class="lesson">
<h3>Querying Trees</h3>
<p>Sometimes, in addition to flat arrays, we need to query trees. Trees pose a challenge because we need to flatten them
into arrays in order to apply filter() and map() operations on them. In this section we'll define a concatAll()
function that we can combine with map() and filter() to query trees.</p>
<h4>Exercise 9: Flatten the movieLists array into an array of video ids</h4>
<p>Let's start by using two nested forEach loops to collect the id of every video in the two-dimensional movieLists
array.</p>
<textarea class="code" rows="60" cols="80">
function() {
var movieLists = [
{
name: "New Releases",
videos: [
{
"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 }]
}
]
},
{
name: "Dramas",
videos: [
{
"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 }]
}
]
}
],
allVideoIdsInMovieLists = [];
// ------------ INSERT CODE HERE! -----------------------------------
// Use two nested forEach loops to flatten the movieLists into a list of
// video ids.
// ------------ INSERT CODE HERE! -----------------------------------
return allVideoIdsInMovieLists;
}
</textarea>
<button class="go">Run</button>
<button class="showAnswer">Show Answer</button>
<button class="fullScreen">Enter Fullscreen</button>
<div class="output"></div>
<pre class="verifier">
// Use filter and map to collect video ids with rating of 5.0
function(str) {
var fun = eval("(" + str + ")"),
videos = fun(),
expected = '[675465,65432445,70111470,654356453]';
videos = videos.sortBy(function(v) { return v });