forked from ReactiveX/learnrx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
4811 lines (4351 loc) · 206 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>
<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">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-37739914-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script src="assets/app/wordlist.js"></script>
<script src="assets/codemirror/codemirror.js"></script>
<script src="assets/app/javascript.js"></script>
<script src="assets/rx/rx.compat.js"></script>
<script src="assets/rx/rx.binding.js"></script>
<script src="assets/rx/rx.async.compat.js"></script>
<script src="assets/rx/rx.time.js"></script>
<script src="assets/jquery/jquery-1.10.2.min.js"></script>
<script>
var seq = function(array, interval) {
interval = interval || 500;
return Rx.Observable.create(function(observer) {
var counter = 0,
lastValue,
timeoutSubscription = null,
unsubscribed = false;
function doWork() {
if (counter === array.length) {
if (lastValue !== undefined) {
observer.onCompleted();
return;
}
}
lastValue = array[counter];
if (lastValue === undefined) {
counter++;
timeoutSubscription = window.setTimeout(doWork, interval);
}
else {
counter++;
observer.onNext(lastValue);
if (!unsubscribed) {
doWork();
}
}
}
doWork();
return function() {
unsubscribed = true;
if (timeoutSubscription !== null) {
testing = window.clearTimeout(timeoutSubscription);
}
};
});
};
var jQueryMock = {
getJSON: function(url, bag) {
if (Math.random() > 0.9) {
if (bag.error) {
bag.error("There was a connectivity error.");
}
}
else if (url.indexOf("abTestInformation") !== -1) {
window.setTimeout(
function() {
bag.success({ urlPrefix: "billboardTest" });
},
500);
}
else if (url.indexOf("config") !== -1) {
window.setTimeout(
function() {
bag.success({ showInstantQueue: true });
},
500);
}
else if (url.indexOf("movieLists") !== -1) {
window.setTimeout(
function() {
bag.success({
list: [
{ name: "Thrillers", videos: [234324,234322314,23,5,435,12,3,234,34,23324] },
{ name: "New Releases", videos: [234324,234322314,23,5,435,12,3,234,34,23324] }
]
});
},
500);
}
else if (url.indexOf("queue") !== -1) {
window.setTimeout(
function() {
bag.success({
list: { name: "Instant Queue", videos: [234324,234322314,23,5,435,12,3,234,34,23324] }
});
},
500);
}
}
};
var Observable = Rx.Observable;
var oldMerge = Observable.prototype.merge;
Observable.prototype.mergeAll = function() {
var args = Array.prototype.slice.call(arguments);
if (arguments.length === 0) {
return Observable.prototype.mergeObservable.apply(this, args);
}
else {
return oldMerge.apply(this, args);
}
}
function deepStringify(obj) {
return JSON.stringify(deepStringifyRecurse(obj));
}
function deepStringifyRecurse(obj) {
var ancestors = [obj],
ancestor,
output = {},
prop,
counter,
value;
if (obj === null || obj === undefined || typeof obj !== "object") {
return obj;
}
ancestor = Object.getPrototypeOf(obj);
while(ancestor !== undefined) {
if (ancestors[ancestors.length-1] === ancestor) {
break;
}
ancestors.push(ancestor);
ancestor = Object.getPrototypeOf(obj);
}
for(counter = ancestors.length-1; counter >= 0; counter--) {
ancestor = ancestors[counter];
for(prop in ancestor) {
output[prop] = deepStringifyRecurse(ancestor[prop]);
}
}
return output;
}
Array.prototype.mergeAll = function() {
var results = [];
this.forEach(function(subArray) {
subArray.forEach(function(itemInArray) {
results.push(itemInArray);
});
});
return results;
};
Array.prototype.flatMap = function(projection) {
return this.
map(function(item) {
return projection(item);
}).
mergeAll();
}
Array.prototype.sortBy = function (keySelector) {
return this.slice().sort(function(a,b) {
var aKey = keySelector(a),
bKey = keySelector(b);
if (aKey > bKey) {
return 1;
}
else if (bKey > aKey) {
return -1;
}
else {
return 0;
}
});
};
Array.prototype.reduce = function(combiner, initialValue) {
var counter,
accumulatedValue;
// If the array is empty, do nothing
if (this.length === 0) {
return this;
}
else {
// If the user didn't pass an initial value, use the first item.
if (arguments.length === 1) {
counter = 1;
accumulatedValue = this[0];
}
else if (arguments.length >= 2) {
counter = 0;
accumulatedValue = initialValue;
}
else {
throw "Invalid arguments.";
}
// Loop through the array, feeding the current value and the result of
// the previous computation back into the combiner function until
// we've exhausted the entire array and are left with only one function.
while(counter < this.length) {
accumulatedValue = combiner(accumulatedValue, this[counter])
counter++;
}
return [accumulatedValue];
}
};
// JSON.stringify(Array.zip([1,2,3],[4,5,6], function(left, right) { return left + right })) === '[5,7,9]' accumulatedValue + currentValue; }); === [6];
Array.zip = function(left, right, combinerFunction) {
var counter,
results = [];
for(counter = 0; counter < Math.min(left.length, right.length); counter++) {
results.push(combinerFunction(left[counter], right[counter]));
}
return results;
};
var codeMirrors = [];
var last = new Date();
</script>
<script>
(function($) {
function pasteIntoInput(el, text) {
el.focus();
if (typeof el.selectionStart == "number") {
var val = el.value;
var selStart = el.selectionStart;
el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
el.selectionEnd = el.selectionStart = selStart + text.length;
} else if (typeof document.selection != "undefined") {
var textRange = document.selection.createRange();
textRange.text = text;
textRange.collapse(false);
textRange.select();
}
}
function allowTabChar(el) {
$(el).keydown(function(e) {
if (e.which == 9) {
pasteIntoInput(this, "\t");
return false;
}
});
// For Opera, which only allows suppression of keypress events, not keydown
$(el).keypress(function(e) {
if (e.which == 9) {
return false;
}
});
}
$.fn.allowTabChar = function() {
if (this.jquery) {
this.each(function() {
if (this.nodeType == 1) {
var nodeName = this.nodeName.toLowerCase();
if (nodeName == "textarea" || (nodeName == "input" && this.type == "text")) {
allowTabChar(this);
}
}
})
}
return this;
}
})(jQuery);
function cancelTab(e) {
if (e.which === 9) {
e.preventDefault();
}
}
window.onload = function() {
function save() {
var answers = [];
$(".lesson").each(function(cnt,item) {
var go = $(".go", item)[0],
code = $(".code", item)[0];
if (window.getComputedStyle(item).visibility !== "hidden") {
answers.push($(code).val());
}
});
localStorage.setItem("newState", JSON.stringify({answers: answers}));
}
// This code adds a reduce question in the middle
var state = localStorage.getItem("state");
if (state) {
state = JSON.parse(state);
state.answers.splice(18,0,$("#q18").val());
localStorage.setItem("newState", JSON.stringify(state));
delete localStorage.state;
}
var state = localStorage.getItem("newState");
if (state) {
state = JSON.parse(state);
var firstUnfinishedQuestion;
$(".lesson").each(function(cnt,item) {
var go = $(".go", item)[0],
code = $(".code", item)[0],
post = $(".post", item)[0];
if (cnt < state.answers.length) {
$(code).val(state.answers[cnt]);
item.style.visibility = "visible";
if (post !== undefined) {
post.style.visibility = "visible";
}
}
else if (cnt === state.answers.length) {
item.style.visibility = "visible";
}
});
}
$(function() {
var lessons = $(".lesson");
lessons.each(function(cnt,item) {
var go = $(".go", item)[0],
code = $(".code", item)[0],
output = $(".output", item)[0],
showAnswer= $(".showAnswer", item)[0],
answer= $(".answer", item)[0],
codeMirror = CodeMirror.fromTextArea(code, {
lineNumbers: true,
matchBrackets: true,
mode: "text/typescript",
tabSize: 4,
indentWithTabs: true
}),
post = $(".post", item)[0],
verifierScript = $(".verifier", item)[0],
controls = $(".control", item);
codeMirrors.push(codeMirror);
go.onclick = function() {
try {
var verifier = eval("(" + verifierScript.innerText + ")");
try {
codeMirror.save();
save();
verifier($(code).val(), item);
if (post !== undefined) {
post.style.visibility = "visible";
}
if (cnt < lessons.length-1) {
lessons[cnt+1].style.visibility = "visible";
}
}
catch(ex) {
alert(ex);
}
}
catch(ex) {
alert(ex);
}
};
if (showAnswer) {
showAnswer.onclick = function() {
codeMirror.setValue(answer.innerText);
};
}
});
});
}
</script>
</head>
<body style="font-family:sans-serif">
<div class="all">
<h1>Functional Programming in Javascript</h1>
<p>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>:</p>
<ol>
<li>map</li>
<li>filter</li>
<li>mergeAll</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>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:delete localStorage.newState; document.location.reload();">restart the lab.</a></p>
<p>This tutorial is on <a href="https://github.com/reactive-extensions/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/reactive-extensions/learnrx/fork_select">fork</a> and send us a pull request. We'll try and fit user-contributed exercises into a narrative.</p>
<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 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 peoples 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.</p>
<h3>Traversing an Array</h3>
<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(var 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) {
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"],
counter;
for(var 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>
<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) {
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>
<p class="post">Notice that forEach let's 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>
</div>
<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 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>
<div class="output">
</div>
<pre class="verifier">
// Projection with with forEach
function(str) {
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 }]
}
],
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>
<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>
<div class="output">
</div>
<pre class="verifier">
// Implement map()
function(str) {
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>
<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>
<div class="output">
</div>
<pre class="verifier">
// Projection with map
function(str) {
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>
<p class="post">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>
</div>
<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 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 ever video with a rating of 5.0
// ------------ INSERT CODE HERE! -----------------------------------
return videos;
}
</textarea><button class="go">Run</button><button class="showAnswer">Show Answer</button>
<div class="output">
</div>
<pre class="verifier">
// Filter with forEach
function(str) {
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>
<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 each result 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>
<div class="output">
</div>
<pre class="verifier">
// Implement filter()
function(str) {
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() let's us express <i>what</i> data we want without requiring us to specify <i>how</i> we want to collect the data.</p>
</div>