-
Notifications
You must be signed in to change notification settings - Fork 34
/
functional-programming.json
1678 lines (1678 loc) · 102 KB
/
functional-programming.json
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
{
"name": "Functional Programming",
"order": 8,
"time": "5 hours",
"helpRoom": "Help",
"challenges": [
{
"id": "587d7b8d367417b2b2512b5b",
"title": "Learn About Functional Programming",
"description": [
"Functional programming is a style of programming where solutions are simple, isolated functions, without any side effects outside of the function scope.",
"<code>INPUT -> PROCESS -> OUTPUT</code>",
"Functional programming is about:",
"1) Isolated functions - there is no dependence on the state of the program, which includes global variables that are subject to change",
"2) Pure functions - the same input always gives the same output",
"3) Functions with limited side effects - any changes, or mutations, to the state of the program outside the function are carefully controlled",
"<hr>",
"The members of freeCodeCamp happen to love tea.",
"In the code editor, the <code>prepareTea</code> and <code>getTea</code> functions are already defined for you. Call the <code>getTea</code> function to get 40 cups of tea for the team, and store them in the <code>tea4TeamFCC</code> variable."
],
"tests": [
{
"text": "The <code>tea4TeamFCC</code> variable should hold 40 cups of tea for the team.",
"testString": "assert(tea4TeamFCC.length === 40, 'The <code>tea4TeamFCC</code> variable should hold 40 cups of tea for the team.');"
},
{
"text": "The <code>tea4TeamFCC</code> variable should hold cups of green tea.",
"testString": "assert(tea4TeamFCC[0] === 'greenTea', 'The <code>tea4TeamFCC</code> variable should hold cups of green tea.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"/**",
" * A long process to prepare tea.",
" * @return {string} A cup of tea.",
" **/",
"const prepareTea = () => 'greenTea';",
"",
"/**",
" * Get given number of cups of tea.",
" * @param {number} numOfCups Number of required cups of tea.",
" * @return {Array<string>} Given amount of tea cups.",
" **/",
"const getTea = (numOfCups) => {",
" const teaCups = [];",
" ",
" for(let cups = 1; cups <= numOfCups; cups += 1) {",
" const teaCup = prepareTea();",
" teaCups.push(teaCup);",
" }",
"",
" return teaCups;",
"};",
"",
"// Add your code below this line",
"",
"const tea4TeamFCC = null; // :(",
"",
"// Add your code above this line",
"",
"console.log(tea4TeamFCC);"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8e367417b2b2512b5c",
"title": "Understand Functional Programming Terminology",
"description": [
"The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common.",
"With that information, we'll need to revisit the <code>getTea</code> function from last challenge to handle various tea requests. We can modify <code>getTea</code> to accept a function as a parameter to be able to change the type of tea it prepares. This makes <code>getTea</code> more flexible, and gives the programmer more control when client requests change.",
"But first, let's cover some functional terminology:",
"<code>Callbacks</code> are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in <code>filter</code>, the callback function tells JavaScript the criteria for how to filter an array.",
"Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called <code>first class</code> functions. In JavaScript, all functions are <code>first class</code> functions.",
"The functions that take a function as an argument, or return a function as a return value are called <code>higher order</code> functions.",
"When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a <code>lambda</code>.",
"<hr>",
"Prepare 27 cups of green tea and 13 cups of black tea and store them in <code>tea4GreenTeamFCC</code> and <code>tea4BlackTeamFCC</code> variables, respectively. Note that the <code>getTea</code> function has been modified so it now takes a function as the first argument.",
"Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons."
],
"tests": [
{
"text": "The <code>tea4GreenTeamFCC</code> variable should hold 27 cups of green tea for the team.",
"testString": "assert(tea4GreenTeamFCC.length === 27, 'The <code>tea4GreenTeamFCC</code> variable should hold 27 cups of green tea for the team.');"
},
{
"text": "The <code>tea4GreenTeamFCC</code> variable should hold cups of green tea.",
"testString": "assert(tea4GreenTeamFCC[0] === 'greenTea', 'The <code>tea4GreenTeamFCC</code> variable should hold cups of green tea.');"
},
{
"text": "The <code>tea4BlackTeamFCC</code> variable should hold 13 cups of black tea.",
"testString": "assert(tea4BlackTeamFCC.length === 13, 'The <code>tea4BlackTeamFCC</code> variable should hold 13 cups of black tea.');"
},
{
"text": "The <code>tea4BlackTeamFCC</code> variable should hold cups of black tea.",
"testString": "assert(tea4BlackTeamFCC[0] === 'blackTea', 'The <code>tea4BlackTeamFCC</code> variable should hold cups of black tea.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"/**",
" * A long process to prepare green tea.",
" * @return {string} A cup of green tea.",
" **/",
"const prepareGreenTea = () => 'greenTea';",
"",
"/**",
" * A long process to prepare black tea.",
" * @return {string} A cup of black tea.",
" **/",
"const prepareBlackTea = () => 'blackTea';",
"",
"/**",
" * Get given number of cups of tea.",
" * @param {function():string} prepareTea The type of tea preparing function.",
" * @param {number} numOfCups Number of required cups of tea.",
" * @return {Array<string>} Given amount of tea cups.",
" **/",
"const getTea = (prepareTea, numOfCups) => {",
" const teaCups = [];",
"",
" for(let cups = 1; cups <= numOfCups; cups += 1) {",
" const teaCup = prepareTea();",
" teaCups.push(teaCup);",
" }",
"",
" return teaCups;",
"};",
"",
"// Add your code below this line",
"",
"const tea4GreenTeamFCC = null; // :(",
"const tea4BlackTeamFCC = null; // :(",
"",
"// Add your code above this line",
"",
"console.log(",
" tea4GreenTeamFCC,",
" tea4BlackTeamFCC",
");"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8e367417b2b2512b5d",
"title": "Understand the Hazards of Using Imperative Code",
"description": [
"Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues.",
"In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task.",
"Often the statements change the state of the program, like updating global variables. A classic example is writing a <code>for</code> loop that gives exact directions to iterate over the indices of an array.",
"In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function.",
"JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the <code>for</code> loop mentioned above, you could call the <code>map</code> method which handles the details of iterating over an array. This helps to avoid semantic errors, like the \"Off By One Errors\" that were covered in the Debugging section.",
"Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code.",
"A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it.",
"The code editor shows an implementation of this functionality with functions for <code>tabOpen()</code>, <code>tabClose()</code>, and <code>join()</code>. The array <code>tabs</code> is part of the Window object that stores the name of the open pages.",
"<h4>Instructions<h4>",
"Run the code in the editor. It's using a method that has side effects in the program, causing incorrect output. The final list of open tabs should be <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code> but the output will be slightly different.",
"Work through the code and see if you can figure out the problem, then advance to the next challenge to learn more."
],
"tests": [
{
"text": "Move ahead to understand the error.",
"testString": "assert(true, 'Move ahead to understand the error.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// tabs is an array of titles of each site open within the window",
"var Window = function(tabs) {",
" this.tabs = tabs; // we keep a record of the array inside the object",
"};",
"",
"// When you join two windows into one window",
"Window.prototype.join = function (otherWindow) {",
" this.tabs = this.tabs.concat(otherWindow.tabs);",
" return this;",
"};",
"",
"// When you open a new tab at the end",
"Window.prototype.tabOpen = function (tab) {",
" this.tabs.push('new tab'); // let's open a new tab for now",
" return this;",
"};",
"",
"// When you close a tab",
"Window.prototype.tabClose = function (index) {",
" var tabsBeforeIndex = this.tabs.splice(0, index); // get the tabs before the tab",
" var tabsAfterIndex = this.tabs.splice(index); // get the tabs after the tab",
"",
" this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together ",
" return this;",
" };",
"",
"// Let's create three browser windows",
"var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites",
"var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites",
"var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites",
"",
"// Now perform the tab opening, closing, and other operations",
"var finalTabs = socialWindow",
" .tabOpen() // Open a new tab for cat memes",
" .join(videoWindow.tabClose(2)) // Close third tab in video window, and join",
" .join(workWindow.tabClose(1).tabOpen());",
"",
"alert(finalTabs.tabs);"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8e367417b2b2512b5e",
"title": "Avoid Mutations and Side Effects Using Functional Programming",
"description": [
"If you haven't already figured it out, the issue in the previous challenge was with the <code>splice</code> call in the <code>tabClose()</code> function. Unfortunately, <code>splice</code> changes the original array it is called on, so the second call to it used a modified array, and gave unexpected results.",
"This is a small example of a much larger pattern - you call a function on a variable, array, or an object, and the function changes the variable or something in the object.",
"One of the core principle of functional programming is to not change things. Changes lead to bugs. It's easier to prevent bugs knowing that your functions don't change anything, including the function arguments or any global variable.",
"The previous example didn't have any complicated operations but the <code>splice</code> method changed the original array, and resulted in a bug.",
"Recall that in functional programming, changing or altering things is called <code>mutation</code>, and the outcome is called a <code>side effect</code>. A function, ideally, should be a <code>pure function</code>, meaning that it does not cause any side effects.",
"Let's try to master this discipline and not alter any variable or object in our code.",
"<hr>",
"Fill in the code for the function <code>incrementer</code> so it returns the value of the global variable <code>fixedValue</code> increased by one."
],
"tests": [
{
"text": "Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.",
"testString": "assert(fixedValue === 4, 'Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.');"
},
{
"text": "Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.",
"testString": "assert(newValue === 5, 'Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global variable",
"var fixedValue = 4;",
"",
"function incrementer () {",
" // Add your code below this line",
" ",
" ",
" // Add your code above this line",
"}",
"",
"var newValue = incrementer(); // Should equal 5",
"console.log(fixedValue); // Should print 4"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8e367417b2b2512b5f",
"title": "Pass Arguments to Avoid External Dependence in a Function",
"description": [
"The last challenge was a step closer to functional programming principles, but there is still something missing.",
"We didn't alter the global variable value, but the function <code>incrementer</code> would not work without the global variable <code>fixedValue</code> being there.",
"Another principle of functional programming is to always declare your dependencies explicitly. This means if a function depends on a variable or object being present, then pass that variable or object directly into the function as an argument.",
"There are several good consequences from this principle. The function is easier to test, you know exactly what input it takes, and it won't depend on anything else in your program.",
"This can give you more confidence when you alter, remove, or add new code. You would know what you can or cannot change and you can see where the potential traps are.",
"Finally, the function would always produce the same output for the same set of inputs, no matter what part of the code executes it.",
"<hr>",
"Let's update the <code>incrementer</code> function to clearly declare its dependencies.",
"Write the <code>incrementer</code> function so it takes an argument, and then increases the value by one."
],
"tests": [
{
"text": "Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.",
"testString": "assert(fixedValue === 4, 'Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.');"
},
{
"text": "Your <code>incrementer</code> function should take a parameter.",
"testString": "assert(code.match(/function\\s+?incrementer\\s*?\\(.+?\\)/g), 'Your <code>incrementer</code> function should take a parameter.');"
},
{
"text": "Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.",
"testString": "assert(newValue === 5, 'Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global variable",
"var fixedValue = 4;",
"",
"// Add your code below this line",
"function incrementer () {",
" ",
" ",
" // Add your code above this line",
"}",
"",
"var newValue = incrementer(fixedValue); // Should equal 5",
"console.log(fixedValue); // Should print 4"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8f367417b2b2512b60",
"title": "Refactor Global Variables Out of Functions",
"description": [
"So far, we have seen two distinct principles for functional programming:",
"1) Don't alter a variable or object - create new variables and objects and return them if need be from a function.",
"2) Declare function arguments - any computation inside a function depends only on the arguments, and not on any global object or variable.",
"Adding one to a number is not very exciting, but we can apply these principles when working with arrays or more complex objects.",
"<hr>",
"Refactor (rewrite) the code so the global array <code>bookList</code> is not changed inside either function. The <code>add</code> function should add the given <code>bookName</code> to the end of an array. The <code>remove</code> function should remove the given <code>bookName</code> from an array. Both functions should return an array, and any new parameters should be added before the <code>bookName</code> one."
],
"tests": [
{
"text": "<code>bookList</code> should not change and still equal <code>[\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"]</code>.",
"testString": "assert(JSON.stringify(bookList) === JSON.stringify([\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"]), '<code>bookList</code> should not change and still equal <code>[\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"]</code>.');"
},
{
"text": "<code>newBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\", \"A Brief History of Time\"]</code>.",
"testString": "assert(JSON.stringify(newBookList) === JSON.stringify(['The Hound of the Baskervilles', 'On The Electrodynamics of Moving Bodies', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']), '<code>newBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\", \"A Brief History of Time\"]</code>.');"
},
{
"text": "<code>newerBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"]</code>.",
"testString": "assert(JSON.stringify(newerBookList) === JSON.stringify(['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae']), '<code>newerBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"]</code>.');"
},
{
"text": "<code>newestBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\", \"A Brief History of Time\"]</code>.",
"testString": "assert(JSON.stringify(newestBookList) === JSON.stringify(['The Hound of the Baskervilles', 'Philosophiæ Naturalis Principia Mathematica', 'Disquisitiones Arithmeticae', 'A Brief History of Time']), '<code>newestBookList</code> should equal <code>[\"The Hound of the Baskervilles\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\", \"A Brief History of Time\"]</code>.');"
}
],
"solutions": [],
"hints": [
"Look at how the functions are called to see the correct order of the parameters.",
"Consider using the concat method instead of push.",
"The slice method returns a new array without modifying the original."
],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global variable",
"var bookList = [\"The Hound of the Baskervilles\", \"On The Electrodynamics of Moving Bodies\", \"Philosophiæ Naturalis Principia Mathematica\", \"Disquisitiones Arithmeticae\"];",
"",
"/* This function should add a book to the list and return the list */",
"// New parameters should come before the bookName one",
"",
"// Add your code below this line",
"function add (bookName) {",
" ",
" return bookList.push(bookName);",
" ",
" // Add your code above this line",
"}",
"",
"/* This function should remove a book from the list and return the list */",
"// New parameters should come before the bookName one",
"",
"// Add your code below this line",
"function remove (bookName) {",
" if (bookList.indexOf(bookName) >= 0) {",
" ",
" return bookList.splice(0, 1, bookName);",
" ",
" // Add your code above this line",
" }",
"}",
"",
"var newBookList = add(bookList, 'A Brief History of Time');",
"var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');",
"var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');",
"",
"console.log(bookList);"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8f367417b2b2512b61",
"title": "Use the map Method to Extract Data from an Array",
"description": [
"So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments.",
"This is only the beginning. As its name suggests, functional programming is centered around a theory of functions.",
"It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered <code>First Class Objects</code> in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments.",
"Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at <code>Array.prototype.map()</code>, or more simply <code>map</code>.",
"Remember that the <code>map</code> method is a way to iterate over each item in an array. It creates a new array (without changing the original one) after applying a callback function to every element.",
"<hr>",
"The <code>watchList</code> array holds objects with information on several movies. Use <code>map</code> to pull the title and rating from <code>watchList</code> and save the new array in the <code>rating</code> variable. The code in the editor currently uses a <code>for</code> loop to do this, replace the loop functionality with your <code>map</code> expression."
],
"tests": [
{
"text": "The <code>watchList</code> variable should not change.",
"testString": "assert(watchList[0].Title === \"Inception\" && watchList[4].Director == \"James Cameron\", 'The <code>watchList</code> variable should not change.');"
},
{
"text": "Your code should not use a <code>for</code> loop.",
"testString": "assert(!code.match(/for\\s*?\\(.+?\\)/g), 'Your code should not use a <code>for</code> loop.');"
},
{
"text": "Your code should use the <code>map</code> method.",
"testString": "assert(code.match(/\\.map/g), 'Your code should use the <code>map</code> method.');"
},
{
"text": "<code>rating</code> should equal <code>[{\"title\":\"Inception\",\"rating\":\"8.8\"},{\"title\":\"Interstellar\",\"rating\":\"8.6\"},{\"title\":\"The Dark Knight\",\"rating\":\"9.0\"},{\"title\":\"Batman Begins\",\"rating\":\"8.3\"},{\"title\":\"Avatar\",\"rating\":\"7.9\"}]</code>.",
"testString": "assert(JSON.stringify(rating) === JSON.stringify([{\"title\":\"Inception\",\"rating\":\"8.8\"},{\"title\":\"Interstellar\",\"rating\":\"8.6\"},{\"title\":\"The Dark Knight\",\"rating\":\"9.0\"},{\"title\":\"Batman Begins\",\"rating\":\"8.3\"},{\"title\":\"Avatar\",\"rating\":\"7.9\"}]), '<code>rating</code> should equal <code>[{\"title\":\"Inception\",\"rating\":\"8.8\"},{\"title\":\"Interstellar\",\"rating\":\"8.6\"},{\"title\":\"The Dark Knight\",\"rating\":\"9.0\"},{\"title\":\"Batman Begins\",\"rating\":\"8.3\"},{\"title\":\"Avatar\",\"rating\":\"7.9\"}]</code>.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global variable",
"var watchList = [",
" { ",
" \"Title\": \"Inception\",",
" \"Year\": \"2010\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"16 Jul 2010\",",
" \"Runtime\": \"148 min\",",
" \"Genre\": \"Action, Adventure, Crime\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Christopher Nolan\",",
" \"Actors\": \"Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy\",",
" \"Plot\": \"A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.\",",
" \"Language\": \"English, Japanese, French\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 4 Oscars. Another 143 wins & 198 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg\",",
" \"Metascore\": \"74\",",
" \"imdbRating\": \"8.8\",",
" \"imdbVotes\": \"1,446,708\",",
" \"imdbID\": \"tt1375666\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" { ",
" \"Title\": \"Interstellar\",",
" \"Year\": \"2014\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"07 Nov 2014\",",
" \"Runtime\": \"169 min\",",
" \"Genre\": \"Adventure, Drama, Sci-Fi\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Jonathan Nolan, Christopher Nolan\",",
" \"Actors\": \"Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow\",",
" \"Plot\": \"A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.\",",
" \"Language\": \"English\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 1 Oscar. Another 39 wins & 132 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg\",",
" \"Metascore\": \"74\",",
" \"imdbRating\": \"8.6\",",
" \"imdbVotes\": \"910,366\",",
" \"imdbID\": \"tt0816692\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" {",
" \"Title\": \"The Dark Knight\",",
" \"Year\": \"2008\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"18 Jul 2008\",",
" \"Runtime\": \"152 min\",",
" \"Genre\": \"Action, Adventure, Crime\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)\",",
" \"Actors\": \"Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine\",",
" \"Plot\": \"When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.\",",
" \"Language\": \"English, Mandarin\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 2 Oscars. Another 146 wins & 142 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg\",",
" \"Metascore\": \"82\",",
" \"imdbRating\": \"9.0\",",
" \"imdbVotes\": \"1,652,832\",",
" \"imdbID\": \"tt0468569\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" { ",
" \"Title\": \"Batman Begins\",",
" \"Year\": \"2005\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"15 Jun 2005\",",
" \"Runtime\": \"140 min\",",
" \"Genre\": \"Action, Adventure\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)\",",
" \"Actors\": \"Christian Bale, Michael Caine, Liam Neeson, Katie Holmes\",",
" \"Plot\": \"After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.\",",
" \"Language\": \"English, Urdu, Mandarin\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Nominated for 1 Oscar. Another 15 wins & 66 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg\",",
" \"Metascore\": \"70\",",
" \"imdbRating\": \"8.3\",",
" \"imdbVotes\": \"972,584\",",
" \"imdbID\": \"tt0372784\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" {",
" \"Title\": \"Avatar\",",
" \"Year\": \"2009\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"18 Dec 2009\",",
" \"Runtime\": \"162 min\",",
" \"Genre\": \"Action, Adventure, Fantasy\",",
" \"Director\": \"James Cameron\",",
" \"Writer\": \"James Cameron\",",
" \"Actors\": \"Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang\",",
" \"Plot\": \"A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.\",",
" \"Language\": \"English, Spanish\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 3 Oscars. Another 80 wins & 121 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg\",",
" \"Metascore\": \"83\",",
" \"imdbRating\": \"7.9\",",
" \"imdbVotes\": \"876,575\",",
" \"imdbID\": \"tt0499549\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" }",
"];",
"",
"// Add your code below this line",
"",
"var rating = [];",
"for(var i=0; i < watchList.length; i++){",
" rating.push({title: watchList[i][\"Title\"], rating: watchList[i][\"imdbRating\"]});",
"}",
"",
"// Add your code above this line",
"",
"console.log(rating); "
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8f367417b2b2512b62",
"title": "Implement map on a Prototype",
"description": [
"As you have seen from applying <code>Array.prototype.map()</code>, or simply <code>map()</code> earlier, the <code>map</code> method returns an array of the same length as the one it was called on. It also doesn't alter the original array, as long as its callback function doesn't.",
"In other words, <code>map</code> is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.",
"It would teach us a lot about <code>map</code> to try to implement a version of it that behaves exactly like the <code>Array.prototype.map()</code> with a <code>for</code> loop or <code>Array.prototype.forEach()</code>.",
"Note: A pure function is allowed to alter local variables defined within its scope, although, it's preferable to avoid that as well.",
"<hr>",
"Write your own <code>Array.prototype.myMap()</code>, which should behave exactly like <code>Array.prototype.map()</code>. You may use a <code>for</code> loop or the <code>forEach</code> method."
],
"tests": [
{
"text": "<code>new_s</code> should equal <code>[46, 130, 196, 10]</code>.",
"testString": "assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]), '<code>new_s</code> should equal <code>[46, 130, 196, 10]</code>.');"
},
{
"text": "Your code should not use the <code>map</code> method.",
"testString": "assert(!code.match(/\\.map/g), 'Your code should not use the <code>map</code> method.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global Array",
"var s = [23, 65, 98, 5];",
"",
"Array.prototype.myMap = function(callback){",
" var newArray = [];",
" // Add your code below this line",
" ",
" // Add your code above this line",
" return newArray;",
"",
"};",
"",
"var new_s = s.myMap(function(item){",
" return item * 2;",
"});"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8f367417b2b2512b63",
"title": "Use the filter Method to Extract Data from an Array",
"description": [
"Another useful array function is <code>Array.prototype.filter()</code>, or simply <code>filter()</code>. The <code>filter</code> method returns a new array which is at most as long as the original array, but usually has fewer items.",
"<code>Filter</code> doesn't alter the original array, just like <code>map</code>. It takes a callback function that applies the logic inside the callback on each element of the array. If an element returns true based on the criteria in the callback function, then it is included in the new array.",
"<hr>",
"The variable <code>watchList</code> holds an array of objects with information on several movies. Use a combination of <code>filter</code> and <code>map</code> to return a new array of objects with only <code>title</code> and <code>rating</code> keys, but where <code>imdbRating</code> is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may want to convert them into numbers to perform mathematical operations on them."
],
"tests": [
{
"text": "The <code>watchList</code> variable should not change.",
"testString": "assert(watchList[0].Title === \"Inception\" && watchList[4].Director == \"James Cameron\", 'The <code>watchList</code> variable should not change.');"
},
{
"text": "Your code should use the <code>filter</code> method.",
"testString": "assert(code.match(/\\.filter/g), 'Your code should use the <code>filter</code> method.');"
},
{
"text": "Your code should not use a <code>for</code> loop.",
"testString": "assert(!code.match(/for\\s*?\\(.+?\\)/g), 'Your code should not use a <code>for</code> loop.');"
},
{
"text": "<code>filteredList</code> should equal <code>[{\"title\": \"Inception\",\"rating\": \"8.8\"},{\"title\": \"Interstellar\",\"rating\": \"8.6\"},{\"title\": \"The Dark Knight\",\"rating\": \"9.0\"},{\"title\": \"Batman Begins\",\"rating\": \"8.3\"}]</code>.",
"testString": "assert.deepEqual(filteredList, [{\"title\": \"Inception\",\"rating\": \"8.8\"},{\"title\": \"Interstellar\",\"rating\": \"8.6\"},{\"title\": \"The Dark Knight\",\"rating\": \"9.0\"},{\"title\": \"Batman Begins\",\"rating\": \"8.3\"}], '<code>filteredList</code> should equal <code>[{\"title\": \"Inception\",\"rating\": \"8.8\"},{\"title\": \"Interstellar\",\"rating\": \"8.6\"},{\"title\": \"The Dark Knight\",\"rating\": \"9.0\"},{\"title\": \"Batman Begins\",\"rating\": \"8.3\"}]</code>.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global variable",
"var watchList = [",
" { ",
" \"Title\": \"Inception\",",
" \"Year\": \"2010\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"16 Jul 2010\",",
" \"Runtime\": \"148 min\",",
" \"Genre\": \"Action, Adventure, Crime\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Christopher Nolan\",",
" \"Actors\": \"Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy\",",
" \"Plot\": \"A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.\",",
" \"Language\": \"English, Japanese, French\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 4 Oscars. Another 143 wins & 198 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg\",",
" \"Metascore\": \"74\",",
" \"imdbRating\": \"8.8\",",
" \"imdbVotes\": \"1,446,708\",",
" \"imdbID\": \"tt1375666\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" { ",
" \"Title\": \"Interstellar\",",
" \"Year\": \"2014\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"07 Nov 2014\",",
" \"Runtime\": \"169 min\",",
" \"Genre\": \"Adventure, Drama, Sci-Fi\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Jonathan Nolan, Christopher Nolan\",",
" \"Actors\": \"Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow\",",
" \"Plot\": \"A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.\",",
" \"Language\": \"English\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 1 Oscar. Another 39 wins & 132 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg\",",
" \"Metascore\": \"74\",",
" \"imdbRating\": \"8.6\",",
" \"imdbVotes\": \"910,366\",",
" \"imdbID\": \"tt0816692\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" {",
" \"Title\": \"The Dark Knight\",",
" \"Year\": \"2008\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"18 Jul 2008\",",
" \"Runtime\": \"152 min\",",
" \"Genre\": \"Action, Adventure, Crime\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)\",",
" \"Actors\": \"Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine\",",
" \"Plot\": \"When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.\",",
" \"Language\": \"English, Mandarin\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 2 Oscars. Another 146 wins & 142 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg\",",
" \"Metascore\": \"82\",",
" \"imdbRating\": \"9.0\",",
" \"imdbVotes\": \"1,652,832\",",
" \"imdbID\": \"tt0468569\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" { ",
" \"Title\": \"Batman Begins\",",
" \"Year\": \"2005\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"15 Jun 2005\",",
" \"Runtime\": \"140 min\",",
" \"Genre\": \"Action, Adventure\",",
" \"Director\": \"Christopher Nolan\",",
" \"Writer\": \"Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)\",",
" \"Actors\": \"Christian Bale, Michael Caine, Liam Neeson, Katie Holmes\",",
" \"Plot\": \"After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.\",",
" \"Language\": \"English, Urdu, Mandarin\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Nominated for 1 Oscar. Another 15 wins & 66 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg\",",
" \"Metascore\": \"70\",",
" \"imdbRating\": \"8.3\",",
" \"imdbVotes\": \"972,584\",",
" \"imdbID\": \"tt0372784\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" },",
" {",
" \"Title\": \"Avatar\",",
" \"Year\": \"2009\",",
" \"Rated\": \"PG-13\",",
" \"Released\": \"18 Dec 2009\",",
" \"Runtime\": \"162 min\",",
" \"Genre\": \"Action, Adventure, Fantasy\",",
" \"Director\": \"James Cameron\",",
" \"Writer\": \"James Cameron\",",
" \"Actors\": \"Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang\",",
" \"Plot\": \"A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.\",",
" \"Language\": \"English, Spanish\",",
" \"Country\": \"USA, UK\",",
" \"Awards\": \"Won 3 Oscars. Another 80 wins & 121 nominations.\",",
" \"Poster\": \"http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg\",",
" \"Metascore\": \"83\",",
" \"imdbRating\": \"7.9\",",
" \"imdbVotes\": \"876,575\",",
" \"imdbID\": \"tt0499549\",",
" \"Type\": \"movie\",",
" \"Response\": \"True\"",
" }",
"];",
"",
"// Add your code below this line",
"",
"var filteredList;",
"",
"// Add your code above this line",
"",
"console.log(filteredList); "
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b8f367417b2b2512b64",
"title": "Implement the filter Method on a Prototype",
"description": [
"It would teach us a lot about the <code>filter</code> method if we try to implement a version of it that behaves exactly like <code>Array.prototype.filter()</code>. It can use either a <code>for</code> loop or <code>Array.prototype.forEach()</code>.",
"Note: A pure function is allowed to alter local variables defined within its scope, although, it's preferable to avoid that as well.",
"<hr>",
"Write your own <code>Array.prototype.myFilter()</code>, which should behave exactly like <code>Array.prototype.filter()</code>. You may use a <code>for</code> loop or the <code>Array.prototype.forEach()</code> method."
],
"tests": [
{
"text": "<code>new_s</code> should equal <code>[23, 65, 5]</code>.",
"testString": "assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]), '<code>new_s</code> should equal <code>[23, 65, 5]</code>.');"
},
{
"text": "Your code should not use the <code>filter</code> method.",
"testString": "assert(!code.match(/\\.filter/g), 'Your code should not use the <code>filter</code> method.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"// the global Array",
"var s = [23, 65, 98, 5];",
"",
"Array.prototype.myFilter = function(callback){",
" var newArray = [];",
" // Add your code below this line",
" ",
" // Add your code above this line",
" return newArray;",
"",
"};",
"",
"var new_s = s.myFilter(function(item){",
" return item % 2 === 1;",
"});"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7b90367417b2b2512b65",
"title": "Return Part of an Array Using the slice Method",
"description": [
"The <code>slice</code> method returns a copy of certain elements of an array. It can take two arguments, the first gives the index of where to begin the slice, the second is the index for where to end the slice (and it's non-inclusive). If the arguments are not provided, the default is to start at the beginning of the array through the end, which is an easy way to make a copy of the entire array. The <code>slice</code> method does not mutate the original array, but returns a new one.",
"Here's an example:",
"<blockquote>var arr = [\"Cat\", \"Dog\", \"Tiger\", \"Zebra\"];<br>var newArray = arr.slice(1, 3);<br>// Sets newArray to [\"Dog\", \"Tiger\"]</blockquote>",
"<hr>",
"Use the <code>slice</code> method in the <code>sliceArray</code> function to return part of the <code>anim</code> array given the provided <code>beginSlice</code> and <code>endSlice</code> indices. The function should return an array."
],
"tests": [
{
"text": "Your code should use the <code>slice</code> method.",
"testString": "assert(code.match(/\\.slice/g), 'Your code should use the <code>slice</code> method.');"
},
{
"text": "The <code>inputAnim</code> variable should not change.",
"testString": "assert(JSON.stringify(inputAnim) === JSON.stringify([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"]), 'The <code>inputAnim</code> variable should not change.');"
},
{
"text": "<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 3)</code> should return <code>[\"Dog\", \"Tiger\"]</code>.",
"testString": "assert(JSON.stringify(sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 3)) === JSON.stringify([\"Dog\", \"Tiger\"]), '<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 3)</code> should return <code>[\"Dog\", \"Tiger\"]</code>.');"
},
{
"text": "<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 0, 1)</code> should return <code>[\"Cat\"]</code>.",
"testString": "assert(JSON.stringify(sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 0, 1)) === JSON.stringify([\"Cat\"]), '<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 0, 1)</code> should return <code>[\"Cat\"]</code>.');"
},
{
"text": "<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 4)</code> should return <code>[\"Dog\", \"Tiger\", \"Zebra\"]</code>.",
"testString": "assert(JSON.stringify(sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 4)) === JSON.stringify([\"Dog\", \"Tiger\", \"Zebra\"]), '<code>sliceArray([\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"], 1, 4)</code> should return <code>[\"Dog\", \"Tiger\", \"Zebra\"]</code>.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function sliceArray(anim, beginSlice, endSlice) {",
" // Add your code below this line",
" ",
" ",
" // Add your code above this line",
"}",
"var inputAnim = [\"Cat\", \"Dog\", \"Tiger\", \"Zebra\", \"Ant\"];",
"sliceArray(inputAnim, 1, 3);"
],
"head": [],
"tail": []
}
}
},
{
"id": "9d7123c8c441eeafaeb5bdef",
"title": "Remove Elements from an Array Using slice Instead of splice",
"description": [
"A common pattern while working with arrays is when you want to remove items and keep the rest of the array. JavaScript offers the <code>splice</code> method for this, which takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the <code>splice</code> method mutates the original array it is called on. Here's an example:",
"<blockquote>var cities = [\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"];<br>cities.splice(3, 1); // Returns \"London\" and deletes it from the cities array<br>// cities is now [\"Chicago\", \"Delhi\", \"Islamabad\", \"Berlin\"]</blockquote>",
"As we saw in the last challenge, the <code>slice</code> method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the <code>slice</code> method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array. Using the <code>slice</code> method instead of <code>splice</code> helps to avoid any array-mutating side effects.",
"<hr>",
"Rewrite the function <code>nonMutatingSplice</code> by using <code>slice</code> instead of <code>splice</code>. It should limit the provided <code>cities</code> array to a length of 3, and return a new array with only the first three items.",
"Do not mutate the original array provided to the function."
],
"tests": [
{
"text": "Your code should use the <code>slice</code> method.",
"testString": "assert(code.match(/\\.slice/g), 'Your code should use the <code>slice</code> method.');"
},
{
"text": "Your code should not use the <code>splice</code> method.",
"testString": "assert(!code.match(/\\.splice/g), 'Your code should not use the <code>splice</code> method.');"
},
{
"text": "The <code>inputCities</code> array should not change.",
"testString": "assert(JSON.stringify(inputCities) === JSON.stringify([\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"]), 'The <code>inputCities</code> array should not change.');"
},
{
"text": "<code>nonMutatingSplice([\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"])</code> should return <code>[\"Chicago\", \"Delhi\", \"Islamabad\"]</code>.",
"testString": "assert(JSON.stringify(nonMutatingSplice([\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"])) === JSON.stringify([\"Chicago\", \"Delhi\", \"Islamabad\"]), '<code>nonMutatingSplice([\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"])</code> should return <code>[\"Chicago\", \"Delhi\", \"Islamabad\"]</code>.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function nonMutatingSplice(cities) {",
" // Add your code below this line",
" return cities.splice(3);",
" ",
" // Add your code above this line",
"}",
"var inputCities = [\"Chicago\", \"Delhi\", \"Islamabad\", \"London\", \"Berlin\"];",
"nonMutatingSplice(inputCities);"
],
"head": [],
"tail": []
}
}
},
{
"id": "587d7da9367417b2b2512b66",
"title": "Combine Two Arrays Using the concat Method",
"description": [
"<code>Concatenation</code> means to join items end to end. JavaScript offers the <code>concat</code> method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to <code>concat</code>, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:",
"<blockquote>[1, 2, 3].concat([4, 5, 6]);<br>// Returns a new array [1, 2, 3, 4, 5, 6]</blockquote>",
"<hr>",
"Use the <code>concat</code> method in the <code>nonMutatingConcat</code> function to concatenate <code>attach</code> to the end of <code>original</code>. The function should return the concatenated array."
],
"tests": [
{
"text": "Your code should use the <code>concat</code> method.",
"testString": "assert(code.match(/\\.concat/g), 'Your code should use the <code>concat</code> method.');"
},
{
"text": "The <code>first</code> array should not change.",
"testString": "assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), 'The <code>first</code> array should not change.');"
},
{
"text": "The <code>second</code> array should not change.",
"testString": "assert(JSON.stringify(second) === JSON.stringify([4, 5]), 'The <code>second</code> array should not change.');"
},
{
"text": "<code>nonMutatingConcat([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.",
"testString": "assert(JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), '<code>nonMutatingConcat([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.');"
}
],
"solutions": [],
"hints": [],
"challengeType": 1,
"files": {
"indexjs": {
"key": "indexjs",
"ext": "js",
"name": "index",
"contents": [
"function nonMutatingConcat(original, attach) {",
" // Add your code below this line",
" ",