Feat: add new Markdown parser (#39800)

and change all the challenges to new `md` format.
This commit is contained in:
Oliver Eyton-Williams
2020-11-27 19:02:05 +01:00
committed by GitHub
parent a07f84c8ec
commit 0bd52f8bd1
2580 changed files with 113436 additions and 111979 deletions

View File

@ -5,10 +5,11 @@ challengeType: 1
forumTopicId: 301226
---
## Description
<section id='description'>
# --description--
Functional programming is all about creating and using non-mutating functions.
The last challenge introduced the <code>concat</code> method as a way to combine arrays into a new one without mutating the original arrays. Compare <code>concat</code> to the <code>push</code> method. <code>Push</code> adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
The last challenge introduced the `concat` method as a way to combine arrays into a new one without mutating the original arrays. Compare `concat` to the `push` method. `Push` adds an item to the end of the same array it is called on, which mutates that array. Here's an example:
```js
var arr = [1, 2, 3];
@ -17,38 +18,50 @@ arr.push([4, 5, 6]);
// Not the functional programming way
```
<code>Concat</code> offers a way to add new items to the end of an array without any mutating side effects.
</section>
`Concat` offers a way to add new items to the end of an array without any mutating side effects.
## Instructions
<section id='instructions'>
Change the <code>nonMutatingPush</code> function so it uses <code>concat</code> to add <code>newItem</code> to the end of <code>original</code> instead of <code>push</code>. The function should return an array.
</section>
# --instructions--
## Tests
<section id='tests'>
Change the `nonMutatingPush` function so it uses `concat` to add `newItem` to the end of `original` instead of `push`. The function should return an array.
```yml
tests:
- text: Your code should use the <code>concat</code> method.
testString: assert(code.match(/\.concat/g));
- text: Your code should not use the <code>push</code> method.
testString: assert(!code.match(/\.?[\s\S]*?push/g));
- text: The <code>first</code> array should not change.
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
- text: The <code>second</code> array should not change.
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]));
- text: <code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.
testString: assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]));
# --hints--
Your code should use the `concat` method.
```js
assert(code.match(/\.concat/g));
```
</section>
Your code should not use the `push` method.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(!code.match(/\.?[\s\S]*?push/g));
```
<div id='js-seed'>
The `first` array should not change.
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
The `second` array should not change.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingPush([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
```js
assert(
JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) ===
JSON.stringify([1, 2, 3, 4, 5])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingPush(original, newItem) {
@ -62,14 +75,7 @@ var second = [4, 5];
nonMutatingPush(first, second);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function nonMutatingPush(original, newItem) {
@ -79,5 +85,3 @@ var first = [1, 2, 3];
var second = [4, 5];
nonMutatingPush(first, second);
```
</section>

View File

@ -5,46 +5,64 @@ challengeType: 1
forumTopicId: 301227
---
## Description
<section id='description'>
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about <code>reduce</code>, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that <code>map</code> and <code>filter</code> are special cases of <code>reduce</code>.
# --description--
The last several challenges covered a number of useful array and string methods that follow functional programming principles. We've also learned about `reduce`, which is a powerful method used to reduce problems to simpler forms. From computing averages to sorting, any array operation can be achieved by applying it. Recall that `map` and `filter` are special cases of `reduce`.
Let's combine what we've learned to solve a practical problem.
Many content management sites (CMS) have the titles of a post added to part of the URL for simple bookmarking purposes. For example, if you write a Medium post titled "Stop Using Reduce", it's likely the URL would have some form of the title string in it (".../stop-using-reduce"). You may have already noticed this on the freeCodeCamp site.
</section>
## Instructions
<section id='instructions'>
Fill in the <code>urlSlug</code> function so it converts a string <code>title</code> and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use <code>replace</code>. Here are the requirements:
# --instructions--
Fill in the `urlSlug` function so it converts a string `title` and returns the hyphenated version for the URL. You can use any of the methods covered in this section, and don't use `replace`. Here are the requirements:
The input is a string with spaces and title-cased words
The output is a string with the spaces between words replaced by a hyphen (<code>-</code>)
The output is a string with the spaces between words replaced by a hyphen (`-`)
The output should be all lower-cased letters
The output should not have any spaces
</section>
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should not use the <code>replace</code> method for this challenge.
testString: assert(!code.match(/\.?[\s\S]*?replace/g));
- text: <code>urlSlug("Winter Is Coming")</code> should return <code>"winter-is-coming"</code>.
testString: assert(urlSlug("Winter Is Coming") === "winter-is-coming");
- text: <code>urlSlug(" Winter Is Coming")</code> should return <code>"winter-is-coming"</code>.
testString: assert(urlSlug(" Winter Is Coming") === "winter-is-coming");
- text: <code>urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")</code> should return <code>"a-mind-needs-books-like-a-sword-needs-a-whetstone"</code>.
testString: assert(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") === "a-mind-needs-books-like-a-sword-needs-a-whetstone");
- text: <code>urlSlug("Hold The Door")</code> should return <code>"hold-the-door"</code>.
testString: assert(urlSlug("Hold The Door") === "hold-the-door");
Your code should not use the `replace` method for this challenge.
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
</section>
`urlSlug("Winter Is Coming")` should return `"winter-is-coming"`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(urlSlug('Winter Is Coming') === 'winter-is-coming');
```
<div id='js-seed'>
`urlSlug(" Winter Is Coming")` should return `"winter-is-coming"`.
```js
assert(urlSlug(' Winter Is Coming') === 'winter-is-coming');
```
`urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")` should return `"a-mind-needs-books-like-a-sword-needs-a-whetstone"`.
```js
assert(
urlSlug('A Mind Needs Books Like A Sword Needs A Whetstone') ===
'a-mind-needs-books-like-a-sword-needs-a-whetstone'
);
```
`urlSlug("Hold The Door")` should return `"hold-the-door"`.
```js
assert(urlSlug('Hold The Door') === 'hold-the-door');
```
# --seed--
## --seed-contents--
```js
// Only change code below this line
@ -55,14 +73,7 @@ function urlSlug(title) {
// Only change code above this line
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// Only change code below this line
@ -70,5 +81,3 @@ function urlSlug(title) {
return title.trim().split(/\s+/).join("-").toLowerCase();
}
```
</section>

View File

@ -5,47 +5,54 @@ challengeType: 1
forumTopicId: 301228
---
## Description
<section id='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.
# --description--
If you haven't already figured it out, the issue in the previous challenge was with the `splice` call in the `tabClose()` function. Unfortunately, `splice` 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 principles 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.
The previous example didn't have any complicated operations but the `splice` method changed the original array, and resulted in a bug.
Recall that in functional programming, changing or altering things is called <dfn>mutation</dfn>, and the outcome is called a <dfn>side effect</dfn>. A function, ideally, should be a <dfn>pure function</dfn>, 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.
</section>
## Instructions
<section id='instructions'>
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.
</section>
# --instructions--
## Tests
<section id='tests'>
Fill in the code for the function `incrementer` so it returns the value of the global variable `fixedValue` increased by one.
```yml
tests:
- text: Your function <code>incrementer</code> should not change the value of <code>fixedValue</code> (which is <code>4</code>).
testString: incrementer(); assert(fixedValue === 4);
- text: Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.
testString: const __newValue = incrementer(); assert(__newValue === 5);
- text: Your <code>incrementer</code> function should return a value based on the global `fixedValue` variable value.
testString: |
(function() {
fixedValue = 10;
const newValue = incrementer();
assert(fixedValue === 10 && newValue === 11);
fixedValue = 4;
})();
# --hints--
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
```js
incrementer();
assert(fixedValue === 4);
```
</section>
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
## Challenge Seed
<section id='challengeSeed'>
```js
const __newValue = incrementer();
assert(__newValue === 5);
```
<div id='js-seed'>
Your `incrementer` function should return a value based on the global `fixedValue` variable value.
```js
(function () {
fixedValue = 10;
const newValue = incrementer();
assert(fixedValue === 10 && newValue === 11);
fixedValue = 4;
})();
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -59,14 +66,7 @@ function incrementer () {
}
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
var fixedValue = 4
@ -75,5 +75,3 @@ function incrementer() {
return fixedValue + 1
}
```
</section>

View File

@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 18221
---
## Description
<section id='description'>
The <code>join</code> method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
# --description--
The `join` method is used to join the elements of an array together to create a string. It takes an argument for the delimiter that is used to separate the array elements in the string.
Here's an example:
```js
@ -16,39 +17,56 @@ var str = arr.join(" ");
// Sets str to "Hello World"
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Use the <code>join</code> method (among others) inside the <code>sentensify</code> function to make a sentence from the words in the string <code>str</code>. The function should return a string. For example, "I-like-Star-Wars" would be converted to "I like Star Wars". For this challenge, do not use the <code>replace</code> method.
</section>
Use the `join` method (among others) inside the `sentensify` function to make a sentence from the words in the string `str`. The function should return a string. For example, "I-like-Star-Wars" would be converted to "I like Star Wars". For this challenge, do not use the `replace` method.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>join</code> method.
testString: assert(code.match(/\.join/g));
- text: Your code should not use the <code>replace</code> method.
testString: assert(!code.match(/\.?[\s\S]*?replace/g));
- text: <code>sentensify("May-the-force-be-with-you")</code> should return a string.
testString: assert(typeof sentensify("May-the-force-be-with-you") === "string");
- text: <code>sentensify("May-the-force-be-with-you")</code> should return <code>"May the force be with you"</code>.
testString: assert(sentensify("May-the-force-be-with-you") === "May the force be with you");
- text: <code>sentensify("The.force.is.strong.with.this.one")</code> should return <code>"The force is strong with this one"</code>.
testString: assert(sentensify("The.force.is.strong.with.this.one") === "The force is strong with this one");
- text: <code>sentensify("There,has,been,an,awakening")</code> should return <code>"There has been an awakening"</code>.
testString: assert(sentensify("There,has,been,an,awakening") === "There has been an awakening");
Your code should use the `join` method.
```js
assert(code.match(/\.join/g));
```
</section>
Your code should not use the `replace` method.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(!code.match(/\.?[\s\S]*?replace/g));
```
<div id='js-seed'>
`sentensify("May-the-force-be-with-you")` should return a string.
```js
assert(typeof sentensify('May-the-force-be-with-you') === 'string');
```
`sentensify("May-the-force-be-with-you")` should return `"May the force be with you"`.
```js
assert(sentensify('May-the-force-be-with-you') === 'May the force be with you');
```
`sentensify("The.force.is.strong.with.this.one")` should return `"The force is strong with this one"`.
```js
assert(
sentensify('The.force.is.strong.with.this.one') ===
'The force is strong with this one'
);
```
`sentensify("There,has,been,an,awakening")` should return `"There has been an awakening"`.
```js
assert(
sentensify('There,has,been,an,awakening') === 'There has been an awakening'
);
```
# --seed--
## --seed-contents--
```js
function sentensify(str) {
@ -60,14 +78,7 @@ function sentensify(str) {
sentensify("May-the-force-be-with-you");
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function sentensify(str) {
@ -76,5 +87,3 @@ function sentensify(str) {
// Only change code above this line
}
```
</section>

View File

@ -5,44 +5,51 @@ challengeType: 1
forumTopicId: 301229
---
## Description
<section id='description'>
<dfn>Concatenation</dfn> 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:
# --description--
<dfn>Concatenation</dfn> means to join items end to end. JavaScript offers the `concat` 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 `concat`, 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:
```js
[1, 2, 3].concat([4, 5, 6]);
// Returns a new array [1, 2, 3, 4, 5, 6]
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
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.
</section>
Use the `concat` method in the `nonMutatingConcat` function to concatenate `attach` to the end of `original`. The function should return the concatenated array.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>concat</code> method.
testString: assert(code.match(/\.concat/g));
- text: The <code>first</code> array should not change.
testString: assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
- text: The <code>second</code> array should not change.
testString: assert(JSON.stringify(second) === JSON.stringify([4, 5]));
- 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]));
Your code should use the `concat` method.
```js
assert(code.match(/\.concat/g));
```
</section>
The `first` array should not change.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]));
```
<div id='js-seed'>
The `second` array should not change.
```js
assert(JSON.stringify(second) === JSON.stringify([4, 5]));
```
`nonMutatingConcat([1, 2, 3], [4, 5])` should return `[1, 2, 3, 4, 5]`.
```js
assert(
JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) ===
JSON.stringify([1, 2, 3, 4, 5])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingConcat(original, attach) {
@ -56,14 +63,7 @@ var second = [4, 5];
nonMutatingConcat(first, second);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function nonMutatingConcat(original, attach) {
@ -75,5 +75,3 @@ var first = [1, 2, 3];
var second = [4, 5];
nonMutatingConcat(first, second);
```
</section>

View File

@ -5,39 +5,35 @@ challengeType: 1
forumTopicId: 301230
---
## Description
# --description--
<section id='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.
You might learn a lot about the <code>map</code> method if you implement your own version of it. It is recommended you use a <code>for</code> loop or <code>Array.prototype.forEach()</code>.
</section>
As you have seen from applying `Array.prototype.map()`, or simply `map()` earlier, the `map` 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.
## Instructions
In other words, `map` is a pure function, and its output depends solely on its inputs. Plus, it takes another function as its argument.
<section id='instructions'>
Write your own <code>Array.prototype.myMap()</code>, which should behave exactly like <code>Array.prototype.map()</code>. You should not use the built-in <code>map</code> method. The <code>Array</code> instance can be accessed in the <code>myMap</code> method using <code>this</code>.
</section>
You might learn a lot about the `map` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
## Tests
# --instructions--
<section id='tests'>
Write your own `Array.prototype.myMap()`, which should behave exactly like `Array.prototype.map()`. You should not use the built-in `map` method. The `Array` instance can be accessed in the `myMap` method using `this`.
```yml
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]));
- text: Your code should not use the <code>map</code> method.
testString: assert(!code.match(/\.?[\s\S]*?map/g));
# --hints--
`new_s` should equal `[46, 130, 196, 10]`.
```js
assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]));
```
</section>
Your code should not use the `map` method.
## Challenge Seed
```js
assert(!code.match(/\.?[\s\S]*?map/g));
```
<section id='challengeSeed'>
# --seed--
<div id='js-seed'>
## --seed-contents--
```js
// The global variable
@ -56,13 +52,7 @@ var new_s = s.myMap(function(item) {
});
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// the global Array
@ -82,5 +72,3 @@ var new_s = s.myMap(function(item) {
return item * 2;
});
```
</section>

View File

@ -5,37 +5,31 @@ challengeType: 1
forumTopicId: 301231
---
## Description
# --description--
<section id='description'>
You might learn a lot about the <code>filter</code> method if you implement your own version of it. It is recommended you use a <code>for</code> loop or <code>Array.prototype.forEach()</code>.
</section>
You might learn a lot about the `filter` method if you implement your own version of it. It is recommended you use a `for` loop or `Array.prototype.forEach()`.
## Instructions
# --instructions--
<section id='instructions'>
Write your own <code>Array.prototype.myFilter()</code>, which should behave exactly like <code>Array.prototype.filter()</code>. You should not use the built-in <code>filter</code> method. The <code>Array</code> instance can be accessed in the <code>myFilter</code> method using <code>this</code>.
</section>
Write your own `Array.prototype.myFilter()`, which should behave exactly like `Array.prototype.filter()`. You should not use the built-in `filter` method. The `Array` instance can be accessed in the `myFilter` method using `this`.
## Tests
# --hints--
<section id='tests'>
`new_s` should equal `[23, 65, 5]`.
```yml
tests:
- text: <code>new_s</code> should equal <code>[23, 65, 5]</code>.
testString: assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
- text: Your code should not use the <code>filter</code> method.
testString: assert(!code.match(/\.?[\s\S]*?filter/g));
```js
assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]));
```
</section>
Your code should not use the `filter` method.
## Challenge Seed
```js
assert(!code.match(/\.?[\s\S]*?filter/g));
```
<section id='challengeSeed'>
# --seed--
<div id='js-seed'>
## --seed-contents--
```js
// The global variable
@ -53,13 +47,7 @@ var new_s = s.myFilter(function(item) {
});
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// the global Array
@ -79,5 +67,3 @@ var new_s = s.myFilter(function(item) {
return item % 2 === 1;
});
```
</section>

View File

@ -5,10 +5,12 @@ challengeType: 1
forumTopicId: 301232
---
## Description
<section id='description'>
# --description--
The <dfn>arity</dfn> of a function is the number of arguments it requires. <dfn>Currying</dfn> a function means to convert a function of N arity into N functions of arity 1.
In other words, it restructures a function so it takes one argument, then returns another function that takes the next argument, and so on.
Here's an example:
```js
@ -37,8 +39,7 @@ var funcForY = curried(1);
console.log(funcForY(2)); // Prints 3
```
Similarly, <dfn>partial application</dfn> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments.
Here's an example:
Similarly, <dfn>partial application</dfn> can be described as applying a few arguments to a function at a time and returning another function that is applied to more arguments. Here's an example:
```js
//Impartial function
@ -49,35 +50,39 @@ var partialFn = impartial.bind(this, 1, 2);
partialFn(10); // Returns 13
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Fill in the body of the <code>add</code> function so it uses currying to add parameters <code>x</code>, <code>y</code>, and <code>z</code>.
</section>
Fill in the body of the `add` function so it uses currying to add parameters `x`, `y`, and `z`.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>add(10)(20)(30)</code> should return <code>60</code>.
testString: assert(add(10)(20)(30) === 60);
- text: <code>add(1)(2)(3)</code> should return <code>6</code>.
testString: assert(add(1)(2)(3) === 6);
- text: <code>add(11)(22)(33)</code> should return <code>66</code>.
testString: assert(add(11)(22)(33) === 66);
- text: Your code should include a final statement that returns <code>x + y + z</code>.
testString: assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
`add(10)(20)(30)` should return `60`.
```js
assert(add(10)(20)(30) === 60);
```
</section>
`add(1)(2)(3)` should return `6`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(add(1)(2)(3) === 6);
```
<div id='js-seed'>
`add(11)(22)(33)` should return `66`.
```js
assert(add(11)(22)(33) === 66);
```
Your code should include a final statement that returns `x + y + z`.
```js
assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g));
```
# --seed--
## --seed-contents--
```js
function add(x) {
@ -89,17 +94,8 @@ function add(x) {
add(10)(20)(30);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
const add = x => y => z => x + y + z
```
</section>

View File

@ -5,40 +5,43 @@ challengeType: 1
forumTopicId: 301233
---
## Description
<section id='description'>
# --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>
`INPUT -> PROCESS -> OUTPUT`
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
</section>
## Instructions
<section id='instructions'>
# --instructions--
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.
</section>
## Tests
<section id='tests'>
In the code editor, the `prepareTea` and `getTea` functions are already defined for you. Call the `getTea` function to get 40 cups of tea for the team, and store them in the `tea4TeamFCC` variable.
```yml
tests:
- text: The <code>tea4TeamFCC</code> variable should hold 40 cups of tea for the team.
testString: assert(tea4TeamFCC.length === 40);
- text: The <code>tea4TeamFCC</code> variable should hold cups of green tea.
testString: assert(tea4TeamFCC[0] === 'greenTea');
# --hints--
The `tea4TeamFCC` variable should hold 40 cups of tea for the team.
```js
assert(tea4TeamFCC.length === 40);
```
</section>
The `tea4TeamFCC` variable should hold cups of green tea.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(tea4TeamFCC[0] === 'greenTea');
```
<div id='js-seed'>
# --seed--
## --seed-contents--
```js
// Function that returns a string representing a cup of green tea
@ -64,14 +67,7 @@ const tea4TeamFCC = null;
// Only change code above this line
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
const prepareTea = () => 'greenTea';
@ -89,5 +85,3 @@ const getTea = (numOfCups) => {
const tea4TeamFCC = getTea(40);
```
</section>

View File

@ -5,43 +5,50 @@ challengeType: 1
forumTopicId: 301234
---
## Description
<section id='description'>
# --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.
We didn't alter the global variable value, but the function `incrementer` would not work without the global variable `fixedValue` 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.
</section>
## Instructions
<section id='instructions'>
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 returns a result after increasing the value by one.
</section>
# --instructions--
## Tests
<section id='tests'>
Let's update the `incrementer` function to clearly declare its dependencies.
```yml
tests:
- text: Your function <code>incrementer</code> should not change the value of <code>fixedValue</code> (which is <code>4</code>).
testString: assert(fixedValue === 4);
- text: Your <code>incrementer</code> function should take an argument.
testString: assert(incrementer.length === 1);
- text: Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.
testString: const __newValue = incrementer(fixedValue); assert(__newValue === 5);
Write the `incrementer` function so it takes an argument, and then returns a result after increasing the value by one.
# --hints--
Your function `incrementer` should not change the value of `fixedValue` (which is `4`).
```js
assert(fixedValue === 4);
```
</section>
Your `incrementer` function should take an argument.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(incrementer.length === 1);
```
<div id='js-seed'>
Your `incrementer` function should return a value that is one larger than the `fixedValue` value.
```js
const __newValue = incrementer(fixedValue);
assert(__newValue === 5);
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -55,14 +62,7 @@ function incrementer () {
}
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// The global variable
@ -77,5 +77,3 @@ function incrementer (fixedValue) {
```
</section>

View File

@ -5,44 +5,83 @@ challengeType: 1
forumTopicId: 301235
---
## Description
<section id='description'>
# --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. Hint: using something like <code>var newArr = arrVar</code>, where <code>arrVar</code> is an array will simply create a reference to the existing variable and not a copy. So changing a value in <code>newArr</code> would change the value in <code>arrVar</code>.
1) Don't alter a variable or object - create new variables and objects and return them if need be from a function. Hint: using something like `var newArr = arrVar`, where `arrVar` is an array will simply create a reference to the existing variable and not a copy. So changing a value in `newArr` would change the value in `arrVar`.
2) Declare function parameters - any computation inside a function depends only on the arguments passed to the function, 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.
</section>
## Instructions
<section id='instructions'>
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 the array passed to it and return a new array (list). The <code>remove</code> function should remove the given <code>bookName</code> from the array passed to it.
# --instructions--
<strong>Note:</strong> Both functions should return an array, and any new parameters should be added before the <code>bookName</code> parameter.
Rewrite the code so the global array `bookList` is not changed inside either function. The `add` function should add the given `bookName` to the end of the array passed to it and return a new array (list). The `remove` function should remove the given `bookName` from the array passed to it.
</section>
**Note:** Both functions should return an array, and any new parameters should be added before the `bookName` parameter.
## Tests
<section id='tests'>
# --hints--
```yml
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"]));
- 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']));
- 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']));
- 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']));
`bookList` should not change and still equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
JSON.stringify(bookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'On The Electrodynamics of Moving Bodies',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae'
])
);
```
</section>
`newBookList` should equal `["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
## Challenge Seed
<section id='challengeSeed'>
```js
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'
])
);
```
<div id='js-seed'>
`newerBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]`.
```js
assert(
JSON.stringify(newerBookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae'
])
);
```
`newestBookList` should equal `["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]`.
```js
assert(
JSON.stringify(newestBookList) ===
JSON.stringify([
'The Hound of the Baskervilles',
'Philosophiæ Naturalis Principia Mathematica',
'Disquisitiones Arithmeticae',
'A Brief History of Time'
])
);
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -76,14 +115,7 @@ var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The El
console.log(bookList);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// The global variable
@ -106,5 +138,3 @@ 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');
```
</section>

View File

@ -5,9 +5,9 @@ challengeType: 1
forumTopicId: 301236
---
## Description
<section id='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:
# --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 `splice` 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 `splice` method mutates the original array it is called on. Here's an example:
```js
var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
@ -15,37 +15,50 @@ cities.splice(3, 1); // Returns "London" and deletes it from the cities array
// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
```
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.
</section>
As we saw in the last challenge, the `slice` method does not mutate the original array, but returns a new one which can be saved into a variable. Recall that the `slice` 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 `slice` method instead of `splice` helps to avoid any array-mutating side effects.
# --instructions--
Rewrite the function `nonMutatingSplice` by using `slice` instead of `splice`. It should limit the provided `cities` array to a length of 3, and return a new array with only the first three items.
## Instructions
<section id='instructions'>
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.
</section>
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>slice</code> method.
testString: assert(code.match(/\.slice/g));
- text: Your code should not use the <code>splice</code> method.
testString: assert(!code.match(/\.?[\s\S]*?splice/g));
- text: The <code>inputCities</code> array should not change.
testString: assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]));
- 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"]));
Your code should use the `slice` method.
```js
assert(code.match(/\.slice/g));
```
</section>
Your code should not use the `splice` method.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(!code.match(/\.?[\s\S]*?splice/g));
```
<div id='js-seed'>
The `inputCities` array should not change.
```js
assert(
JSON.stringify(inputCities) ===
JSON.stringify(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
);
```
`nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])` should return `["Chicago", "Delhi", "Islamabad"]`.
```js
assert(
JSON.stringify(
nonMutatingSplice(['Chicago', 'Delhi', 'Islamabad', 'London', 'Berlin'])
) === JSON.stringify(['Chicago', 'Delhi', 'Islamabad'])
);
```
# --seed--
## --seed-contents--
```js
function nonMutatingSplice(cities) {
@ -58,14 +71,7 @@ var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function nonMutatingSplice(cities) {
@ -76,5 +82,3 @@ function nonMutatingSplice(cities) {
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
```
</section>

View File

@ -5,40 +5,52 @@ challengeType: 1
forumTopicId: 301237
---
## Description
<section id='description'>
A side effect of the <code>sort</code> method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that <code>slice</code> and <code>concat</code> return a new array), then run the <code>sort</code> method.
</section>
# --description--
## Instructions
<section id='instructions'>
Use the <code>sort</code> method in the <code>nonMutatingSort</code> function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the <code>globalArray</code> variable.
</section>
A side effect of the `sort` method is that it changes the order of the elements in the original array. In other words, it mutates the array in place. One way to avoid this is to first concatenate an empty array to the one being sorted (remember that `slice` and `concat` return a new array), then run the `sort` method.
## Tests
<section id='tests'>
# --instructions--
```yml
tests:
- text: Your code should use the <code>sort</code> method.
testString: assert(nonMutatingSort.toString().match(/\.sort/g));
- text: The <code>globalArray</code> variable should not change.
testString: assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
- text: <code>nonMutatingSort(globalArray)</code> should return <code>[2, 3, 5, 6, 9]</code>.
testString: assert(JSON.stringify(nonMutatingSort(globalArray)) === JSON.stringify([2, 3, 5, 6, 9]));
- text: <code>nonMutatingSort(globalArray)</code> should not be hard coded.
testString: assert(!nonMutatingSort.toString().match(/[23569]/g));
- text: The function should return a new array, not the array passed to it.
testString: assert(nonMutatingSort(globalArray) !== globalArray);
Use the `sort` method in the `nonMutatingSort` function to sort the elements of an array in ascending order. The function should return a new array, and not mutate the `globalArray` variable.
# --hints--
Your code should use the `sort` method.
```js
assert(nonMutatingSort.toString().match(/\.sort/g));
```
</section>
The `globalArray` variable should not change.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]));
```
<div id='js-seed'>
`nonMutatingSort(globalArray)` should return `[2, 3, 5, 6, 9]`.
```js
assert(
JSON.stringify(nonMutatingSort(globalArray)) ===
JSON.stringify([2, 3, 5, 6, 9])
);
```
`nonMutatingSort(globalArray)` should not be hard coded.
```js
assert(!nonMutatingSort.toString().match(/[23569]/g));
```
The function should return a new array, not the array passed to it.
```js
assert(nonMutatingSort(globalArray) !== globalArray);
```
# --seed--
## --seed-contents--
```js
var globalArray = [5, 6, 3, 2, 9];
@ -51,14 +63,7 @@ function nonMutatingSort(arr) {
nonMutatingSort(globalArray);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
var globalArray = [5, 6, 3, 2, 9];
@ -69,5 +74,3 @@ function nonMutatingSort(arr) {
}
nonMutatingSort(globalArray);
```
</section>

View File

@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 301239
---
## Description
<section id='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.
# --description--
The `slice` 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 `slice` method does not mutate the original array, but returns a new one.
Here's an example:
```js
@ -16,37 +17,57 @@ var newArray = arr.slice(1, 3);
// Sets newArray to ["Dog", "Tiger"]
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
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.
</section>
Use the `slice` method in the `sliceArray` function to return part of the `anim` array given the provided `beginSlice` and `endSlice` indices. The function should return an array.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>slice</code> method.
testString: assert(code.match(/\.slice/g));
- text: The <code>inputAnim</code> variable should not change.
testString: assert(JSON.stringify(inputAnim) === JSON.stringify(["Cat", "Dog", "Tiger", "Zebra", "Ant"]));
- 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"]));
- 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"]));
- 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"]));
Your code should use the `slice` method.
```js
assert(code.match(/\.slice/g));
```
</section>
The `inputAnim` variable should not change.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
JSON.stringify(inputAnim) ===
JSON.stringify(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'])
);
```
<div id='js-seed'>
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)` should return `["Dog", "Tiger"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 3)) ===
JSON.stringify(['Dog', 'Tiger'])
);
```
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)` should return `["Cat"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 0, 1)) ===
JSON.stringify(['Cat'])
);
```
`sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)` should return `["Dog", "Tiger", "Zebra"]`.
```js
assert(
JSON.stringify(sliceArray(['Cat', 'Dog', 'Tiger', 'Zebra', 'Ant'], 1, 4)) ===
JSON.stringify(['Dog', 'Tiger', 'Zebra'])
);
```
# --seed--
## --seed-contents--
```js
function sliceArray(anim, beginSlice, endSlice) {
@ -59,14 +80,7 @@ var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function sliceArray(anim, beginSlice, endSlice) {
@ -77,5 +91,3 @@ function sliceArray(anim, beginSlice, endSlice) {
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
sliceArray(inputAnim, 1, 3);
```
</section>

View File

@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 18303
---
## Description
<section id='description'>
The <code>sort</code> method sorts the elements of an array according to the callback function.
# --description--
The `sort` method sorts the elements of an array according to the callback function.
For example:
```js
@ -28,40 +29,50 @@ reverseAlpha(['l', 'h', 'z', 'b', 's']);
// Returns ['z', 's', 'l', 'h', 'b']
```
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called <code>compareFunction</code>, is supplied, the array elements are sorted according to the return value of the <code>compareFunction</code>:
If <code>compareFunction(a,b)</code> returns a value less than 0 for two elements <code>a</code> and <code>b</code>, then <code>a</code> will come before <code>b</code>.
If <code>compareFunction(a,b)</code> returns a value greater than 0 for two elements <code>a</code> and <code>b</code>, then <code>b</code> will come before <code>a</code>.
If <code>compareFunction(a,b)</code> returns a value equal to 0 for two elements <code>a</code> and <code>b</code>, then <code>a</code> and <code>b</code> will remain unchanged.
JavaScript's default sorting method is by string Unicode point value, which may return unexpected results. Therefore, it is encouraged to provide a callback function to specify how to sort the array items. When such a callback function, normally called `compareFunction`, is supplied, the array elements are sorted according to the return value of the `compareFunction`: If `compareFunction(a,b)` returns a value less than 0 for two elements `a` and `b`, then `a` will come before `b`. If `compareFunction(a,b)` returns a value greater than 0 for two elements `a` and `b`, then `b` will come before `a`. If `compareFunction(a,b)` returns a value equal to 0 for two elements `a` and `b`, then `a` and `b` will remain unchanged.
</section>
# --instructions--
## Instructions
<section id='instructions'>
Use the <code>sort</code> method in the <code>alphabeticalOrder</code> function to sort the elements of <code>arr</code> in alphabetical order.
</section>
Use the `sort` method in the `alphabeticalOrder` function to sort the elements of `arr` in alphabetical order.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>sort</code> method.
testString: assert(code.match(/\.sort/g));
- text: <code>alphabeticalOrder(["a", "d", "c", "a", "z", "g"])</code> should return <code>["a", "a", "c", "d", "g", "z"]</code>.
testString: assert(JSON.stringify(alphabeticalOrder(["a", "d", "c", "a", "z", "g"])) === JSON.stringify(["a", "a", "c", "d", "g", "z"]));
- text: <code>alphabeticalOrder(["x", "h", "a", "m", "n", "m"])</code> should return <code>["a", "h", "m", "m", "n", "x"]</code>.
testString: assert(JSON.stringify(alphabeticalOrder(["x", "h", "a", "m", "n", "m"])) === JSON.stringify(["a", "h", "m", "m", "n", "x"]));
- text: <code>alphabeticalOrder(["a", "a", "a", "a", "x", "t"])</code> should return <code>["a", "a", "a", "a", "t", "x"]</code>.
testString: assert(JSON.stringify(alphabeticalOrder(["a", "a", "a", "a", "x", "t"])) === JSON.stringify(["a", "a", "a", "a", "t", "x"]));
Your code should use the `sort` method.
```js
assert(code.match(/\.sort/g));
```
</section>
`alphabeticalOrder(["a", "d", "c", "a", "z", "g"])` should return `["a", "a", "c", "d", "g", "z"]`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
JSON.stringify(alphabeticalOrder(['a', 'd', 'c', 'a', 'z', 'g'])) ===
JSON.stringify(['a', 'a', 'c', 'd', 'g', 'z'])
);
```
<div id='js-seed'>
`alphabeticalOrder(["x", "h", "a", "m", "n", "m"])` should return `["a", "h", "m", "m", "n", "x"]`.
```js
assert(
JSON.stringify(alphabeticalOrder(['x', 'h', 'a', 'm', 'n', 'm'])) ===
JSON.stringify(['a', 'h', 'm', 'm', 'n', 'x'])
);
```
`alphabeticalOrder(["a", "a", "a", "a", "x", "t"])` should return `["a", "a", "a", "a", "t", "x"]`.
```js
assert(
JSON.stringify(alphabeticalOrder(['a', 'a', 'a', 'a', 'x', 't'])) ===
JSON.stringify(['a', 'a', 'a', 'a', 't', 'x'])
);
```
# --seed--
## --seed-contents--
```js
function alphabeticalOrder(arr) {
@ -73,14 +84,7 @@ function alphabeticalOrder(arr) {
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function alphabeticalOrder(arr) {
@ -90,5 +94,3 @@ function alphabeticalOrder(arr) {
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
```
</section>

View File

@ -5,9 +5,10 @@ challengeType: 1
forumTopicId: 18305
---
## Description
<section id='description'>
The <code>split</code> method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.
# --description--
The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string.
Here are two examples that split one string by spaces, then another by digits using a regular expression:
```js
@ -20,36 +21,50 @@ var byDigits = otherString.split(/\d/);
// Sets byDigits to ["How", "are", "you", "today"]
```
Since strings are immutable, the <code>split</code> method makes it easier to work with them.
</section>
Since strings are immutable, the `split` method makes it easier to work with them.
## Instructions
<section id='instructions'>
Use the <code>split</code> method inside the <code>splitify</code> function to split <code>str</code> into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
</section>
# --instructions--
## Tests
<section id='tests'>
Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation.
```yml
tests:
- text: Your code should use the <code>split</code> method.
testString: assert(code.match(/\.split/g));
- text: <code>splitify("Hello World,I-am code")</code> should return <code>["Hello", "World", "I", "am", "code"]</code>.
testString: assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"]));
- text: <code>splitify("Earth-is-our home")</code> should return <code>["Earth", "is", "our", "home"]</code>.
testString: assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"]));
- text: <code>splitify("This.is.a-sentence")</code> should return <code>["This", "is", "a", "sentence"]</code>.
testString: assert(JSON.stringify(splitify("This.is.a-sentence")) === JSON.stringify(["This", "is", "a", "sentence"]));
# --hints--
Your code should use the `split` method.
```js
assert(code.match(/\.split/g));
```
</section>
`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(
JSON.stringify(splitify('Hello World,I-am code')) ===
JSON.stringify(['Hello', 'World', 'I', 'am', 'code'])
);
```
<div id='js-seed'>
`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`.
```js
assert(
JSON.stringify(splitify('Earth-is-our home')) ===
JSON.stringify(['Earth', 'is', 'our', 'home'])
);
```
`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`.
```js
assert(
JSON.stringify(splitify('This.is.a-sentence')) ===
JSON.stringify(['This', 'is', 'a', 'sentence'])
);
```
# --seed--
## --seed-contents--
```js
function splitify(str) {
@ -61,14 +76,7 @@ function splitify(str) {
splitify("Hello World,I-am code");
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function splitify(str) {
@ -77,5 +85,3 @@ function splitify(str) {
// Only change code above this line
}
```
</section>

View File

@ -5,45 +5,57 @@ challengeType: 1
forumTopicId: 301240
---
## Description
<section id='description'>
# --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.
With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change.
But first, let's cover some functional terminology:
<dfn>Callbacks</dfn> 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.
<dfn>Callbacks</dfn> 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 `filter`, 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 <dfn>first class</dfn> functions. In JavaScript, all functions are first class functions.
The functions that take a function as an argument, or return a function as a return value are called <dfn>higher order</dfn> 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 <dfn>lambda</dfn>.
</section>
## Instructions
<section id='instructions'>
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.
# --instructions--
Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` 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.
</section>
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>tea4GreenTeamFCC</code> variable should hold 27 cups of green tea for the team.
testString: assert(tea4GreenTeamFCC.length === 27);
- text: The <code>tea4GreenTeamFCC</code> variable should hold cups of green tea.
testString: assert(tea4GreenTeamFCC[0] === 'greenTea');
- text: The <code>tea4BlackTeamFCC</code> variable should hold 13 cups of black tea.
testString: assert(tea4BlackTeamFCC.length === 13);
- text: The <code>tea4BlackTeamFCC</code> variable should hold cups of black tea.
testString: assert(tea4BlackTeamFCC[0] === 'blackTea');
The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team.
```js
assert(tea4GreenTeamFCC.length === 27);
```
</section>
The `tea4GreenTeamFCC` variable should hold cups of green tea.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(tea4GreenTeamFCC[0] === 'greenTea');
```
<div id='js-seed'>
The `tea4BlackTeamFCC` variable should hold 13 cups of black tea.
```js
assert(tea4BlackTeamFCC.length === 13);
```
The `tea4BlackTeamFCC` variable should hold cups of black tea.
```js
assert(tea4BlackTeamFCC[0] === 'blackTea');
```
# --seed--
## --seed-contents--
```js
// Function that returns a string representing a cup of green tea
@ -78,14 +90,7 @@ console.log(
);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
const prepareGreenTea = () => 'greenTea';
@ -104,5 +109,3 @@ const getTea = (prepareTea, numOfCups) => {
const tea4BlackTeamFCC = getTea(prepareBlackTea, 13);
const tea4GreenTeamFCC = getTea(prepareGreenTea, 27);
```
</section>

View File

@ -5,44 +5,56 @@ challengeType: 1
forumTopicId: 301241
---
## Description
<section id='description'>
# --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.
Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` 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.
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 `for` loop mentioned above, you could call the `map` 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.
The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages.
</section>
# --instructions--
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different.
## Instructions
<section id='instructions'>
Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in <code>finalTabs.tabs</code>, should be <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code> but the list produced by the code is slightly different.
Change `Window.prototype.tabClose` so that it removes the correct tab.
Change <code>Window.prototype.tabClose</code> so that it removes the correct tab.
</section>
# --hints--
## Tests
<section id='tests'>
```yml
tests:
- text: <code>finalTabs.tabs</code> should be <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code>
testString: assert.deepEqual(finalTabs.tabs, ['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab'])
`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']`
```js
assert.deepEqual(finalTabs.tabs, [
'FB',
'Gitter',
'Reddit',
'Twitter',
'Medium',
'new tab',
'Netflix',
'YouTube',
'Vine',
'GMail',
'Work mail',
'Docs',
'freeCodeCamp',
'new tab'
]);
```
</section>
# --seed--
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
## --seed-contents--
```js
// tabs is an array of titles of each site open within the window
@ -90,14 +102,7 @@ var finalTabs = socialWindow
console.log(finalTabs.tabs);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// tabs is an array of titles of each site open within the window
@ -137,5 +142,3 @@ var finalTabs = socialWindow
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen());
```
</section>

View File

@ -1,50 +1,74 @@
---
id: 587d7b88367417b2b2512b45
title: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
title: 'Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem'
challengeType: 1
forumTopicId: 301311
---
## Description
# --description--
<section id='description'>
Now that you have worked through a few challenges using higher-order functions like <code>map()</code>, <code>filter()</code>, and <code>reduce()</code>, you now get to apply them to solve a more complex challenge.
</section>
Now that you have worked through a few challenges using higher-order functions like `map()`, `filter()`, and `reduce()`, you now get to apply them to solve a more complex challenge.
## Instructions
# --instructions--
<section id='instructions'>
We have defined a function named <code>squareList</code>. You need to complete the code for the <code>squareList</code> function using any combination of <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> so that it returns a new array containing only the square of <em>only</em> the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is <code>[-3, 4.8, 5, 3, -3.2]</code>.
<strong>Note:</strong> Your function should not use any kind of <code>for</code> or <code>while</code> loops or the <code>forEach()</code> function.
</section>
We have defined a function named `squareList`. You need to complete the code for the `squareList` function using any combination of `map()`, `filter()`, and `reduce()` so that it returns a new array containing only the square of *only* the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is `[-3, 4.8, 5, 3, -3.2]`.
## Tests
**Note:** Your function should not use any kind of `for` or `while` loops or the `forEach()` function.
<section id='tests'>
# --hints--
```yml
tests:
- text: <code>squareList</code> should be a <code>function</code>.
testString: assert.typeOf(squareList, 'function'), '<code>squareList</code> should be a <code>function</code>';
- text: <code>for</code>, <code>while</code>, and <code>forEach</code> should not be used.
testString: assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
- text: <code>map</code>, <code>filter</code>, or <code>reduce</code> should be used.
testString: assert(__helpers.removeWhiteSpace(__helpers.removeJSComments(code)).match(/\.(map|filter|reduce)\(/g));
- text: The function should return an <code>array</code>.
testString: assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
- text: <code>squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])</code> should return <code>[16, 1764, 36]</code>.
testString: assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [16, 1764, 36]);
- text: <code>squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])</code> should return <code>[9, 100, 49]</code>.
testString: assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [9, 100, 49]);
`squareList` should be a `function`.
```js
assert.typeOf(squareList, 'function'),
'<code>squareList</code> should be a <code>function</code>';
```
</section>
`for`, `while`, and `forEach` should not be used.
## Challenge Seed
```js
assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
```
<section id='challengeSeed'>
`map`, `filter`, or `reduce` should be used.
<div id='js-seed'>
```js
assert(
__helpers
.removeWhiteSpace(__helpers.removeJSComments(code))
.match(/\.(map|filter|reduce)\(/g)
);
```
The function should return an `array`.
```js
assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
```
`squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])` should return `[16, 1764, 36]`.
```js
assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [
16,
1764,
36
]);
```
`squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])` should return `[9, 100, 49]`.
```js
assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [
9,
100,
49
]);
```
# --seed--
## --seed-contents--
```js
const squareList = arr => {
@ -57,13 +81,7 @@ const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
const squareList = arr => {
@ -76,5 +94,3 @@ const squareList = arr => {
return squaredIntegers;
};
```
</section>

View File

@ -5,10 +5,11 @@ challengeType: 1
forumTopicId: 301312
---
## Description
<section id='description'>
The <code>every</code> method works with arrays to check if <em>every</em> element passes a particular test. It returns a Boolean value - <code>true</code> if all values meet the criteria, <code>false</code> if not.
For example, the following code would check if every element in the <code>numbers</code> array is less than 10:
# --description--
The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not.
For example, the following code would check if every element in the `numbers` array is less than 10:
```js
var numbers = [1, 5, 8, 0, 10, 11];
@ -18,35 +19,39 @@ numbers.every(function(currentValue) {
// Returns false
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Use the <code>every</code> method inside the <code>checkPositive</code> function to check if every element in <code>arr</code> is positive. The function should return a Boolean value.
</section>
Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>every</code> method.
testString: assert(code.match(/\.every/g));
- text: <code>checkPositive([1, 2, 3, -4, 5])</code> should return <code>false</code>.
testString: assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
- text: <code>checkPositive([1, 2, 3, 4, 5])</code> should return <code>true</code>.
testString: assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
- text: <code>checkPositive([1, -2, 3, -4, 5])</code> should return <code>false</code>.
testString: assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
Your code should use the `every` method.
```js
assert(code.match(/\.every/g));
```
</section>
`checkPositive([1, 2, 3, -4, 5])` should return `false`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert.isFalse(checkPositive([1, 2, 3, -4, 5]));
```
<div id='js-seed'>
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
```js
assert.isTrue(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([1, -2, 3, -4, 5])` should return `false`.
```js
assert.isFalse(checkPositive([1, -2, 3, -4, 5]));
```
# --seed--
## --seed-contents--
```js
function checkPositive(arr) {
@ -58,14 +63,7 @@ function checkPositive(arr) {
checkPositive([1, 2, 3, -4, 5]);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function checkPositive(arr) {
@ -75,5 +73,3 @@ function checkPositive(arr) {
}
checkPositive([1, 2, 3, -4, 5]);
```
</section>

View File

@ -5,12 +5,15 @@ challengeType: 1
forumTopicId: 18179
---
## Description
<section id='description'>
Another useful array function is <code>Array.prototype.filter()</code>, or simply <code>filter()</code>.
<code>filter</code> calls a function on each element of an array and returns a new array containing only the elements for which that function returns <code>true</code>. In other words, it filters the array, based on the function passed to it. Like <code>map</code>, it does this without needing to modify the original array.
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the <code>filter</code> method was called.
See below for an example using the <code>filter</code> method on the <code>users</code> array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback.
# --description--
Another useful array function is `Array.prototype.filter()`, or simply `filter()`.
`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array.
The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called.
See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback.
```js
const users = [
@ -23,35 +26,46 @@ const usersUnder30 = users.filter(user => user.age < 30);
console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
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> on <code>watchList</code> to assign a new array of objects with only <code>title</code> and <code>rating</code> keys. The new array should only include objects 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 need to convert them into numbers to perform mathematical operations on them.
</section>
The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>watchList</code> variable should not change.
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: Your code should use the <code>filter</code> method.
testString: assert(code.match(/\.filter/g));
- text: Your code should not use a <code>for</code> loop.
testString: assert(!code.match(/for\s*?\([\s\S]*?\)/g));
- 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"}]);'
The `watchList` variable should not change.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
</section>
Your code should use the `filter` method.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(code.match(/\.filter/g));
```
<div id='js-seed'>
Your code should not use a `for` loop.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`.
```js
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' }
]);
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -177,14 +191,7 @@ var filteredList;
console.log(filteredList);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// The global variable
@ -305,5 +312,3 @@ var watchList = [
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
// Only change code above this line
```
</section>

View File

@ -5,15 +5,21 @@ challengeType: 1
forumTopicId: 18214
---
## Description
<section id='description'>
# --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 <dfn>first class objects</dfn> 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>.
The <code>map</code> method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array.
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the <code>map</code> method was called.
See below for an example using the <code>map</code> method on the <code>users</code> array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback.
Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`.
The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array.
When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called.
See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback.
```js
const users = [
@ -26,35 +32,47 @@ const names = users.map(user => user.name);
console.log(names); // [ 'John', 'Amy', 'camperCat' ]
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
The <code>watchList</code> array holds objects with information on several movies. Use <code>map</code> on <code>watchList</code> to assign a new array of objects with only <code>title</code> and <code>rating</code> keys to the <code>ratings</code> variable. The code in the editor currently uses a <code>for</code> loop to do this, so you should replace the loop functionality with your <code>map</code> expression.
</section>
The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys to the `ratings` variable. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>watchList</code> variable should not change.
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: Your code should not use a <code>for</code> loop.
testString: assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
- text: Your code should use the <code>map</code> method.
testString: assert(code.match(/\.map/g));
- text: <code>ratings</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.deepEqual(ratings, [{"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"}]);
The `watchList` variable should not change.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
</section>
Your code should not use a `for` loop.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/));
```
<div id='js-seed'>
Your code should use the `map` method.
```js
assert(code.match(/\.map/g));
```
`ratings` should equal `[{"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"}]`.
```js
assert.deepEqual(ratings, [
{ 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' }
]);
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -183,12 +201,7 @@ for(var i=0; i < watchList.length; i++){
console.log(JSON.stringify(ratings));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// The global variable
@ -312,5 +325,3 @@ var ratings = watchList.map(function(movie) {
}
});
```
</section>

View File

@ -5,19 +5,17 @@ challengeType: 1
forumTopicId: 301313
---
## Description
<section id='description'>
# --description--
<code>Array.prototype.reduce()</code>, or simply <code>reduce()</code>, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the <code>reduce</code> method.
`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method.
The <code>reduce</code> method allows for more general forms of array processing, and it's possible to show that both <code>filter</code> and <code>map</code> can be derived as special applications of <code>reduce</code>.
The <code>reduce</code> method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.
The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration.
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which <code>reduce</code> is called.
The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called.
In addition to the callback function, <code>reduce</code> has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.
In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator.
See below for an example using <code>reduce</code> on the <code>users</code> array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments.
See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments.
```js
const users = [
@ -46,37 +44,47 @@ const usersObj = users.reduce((obj, user) => {
console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 }
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
The variable <code>watchList</code> holds an array of objects with information on several movies. Use <code>reduce</code> to find the average IMDB rating of the movies <strong>directed by Christopher Nolan</strong>. Recall from prior challenges how to <code>filter</code> data and <code>map</code> over it to pull what you need. You may need to create other variables, and return the average rating from <code>getRating</code> function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.
</section>
The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies **directed by Christopher Nolan**. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: The <code>watchList</code> variable should not change.
testString: assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron");
- text: Your code should use the <code>reduce</code> method.
testString: assert(code.match(/\.reduce/g));
- text: The <code>getRating(watchList)</code> should equal 8.675.
testString: assert(getRating(watchList) === 8.675);
- text: Your code should not use a <code>for</code> loop.
testString: assert(!code.match(/for\s*?\([\s\S]*?\)/g));
- text: Your code should return correct output after modifying the <code>watchList</code> object.
testString: assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
The `watchList` variable should not change.
```js
assert(
watchList[0].Title === 'Inception' && watchList[4].Director == 'James Cameron'
);
```
</section>
Your code should use the `reduce` method.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(code.match(/\.reduce/g));
```
<div id='js-seed'>
The `getRating(watchList)` should equal 8.675.
```js
assert(getRating(watchList) === 8.675);
```
Your code should not use a `for` loop.
```js
assert(!code.match(/for\s*?\([\s\S]*?\)/g));
```
Your code should return correct output after modifying the `watchList` object.
```js
assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55);
```
# --seed--
## --seed-contents--
```js
// The global variable
@ -204,14 +212,7 @@ function getRating(watchList){
console.log(getRating(watchList));
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
// The global variable
@ -336,7 +337,4 @@ function getRating(watchList){
averageRating = rating.reduce((accum, curr) => accum + curr)/rating.length;
return averageRating;
}
```
</section>

View File

@ -5,10 +5,11 @@ challengeType: 1
forumTopicId: 301314
---
## Description
<section id='description'>
The <code>some</code> method works with arrays to check if <em>any</em> element passes a particular test. It returns a Boolean value - <code>true</code> if any of the values meet the criteria, <code>false</code> if not.
For example, the following code would check if any element in the <code>numbers</code> array is less than 10:
# --description--
The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not.
For example, the following code would check if any element in the `numbers` array is less than 10:
```js
var numbers = [10, 50, 8, 220, 110, 11];
@ -18,35 +19,39 @@ numbers.some(function(currentValue) {
// Returns true
```
</section>
# --instructions--
## Instructions
<section id='instructions'>
Use the <code>some</code> method inside the <code>checkPositive</code> function to check if any element in <code>arr</code> is positive. The function should return a Boolean value.
</section>
Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value.
## Tests
<section id='tests'>
# --hints--
```yml
tests:
- text: Your code should use the <code>some</code> method.
testString: assert(code.match(/\.some/g));
- text: <code>checkPositive([1, 2, 3, -4, 5])</code> should return <code>true</code>.
testString: assert(checkPositive([1, 2, 3, -4, 5]));
- text: <code>checkPositive([1, 2, 3, 4, 5])</code> should return <code>true</code>.
testString: assert(checkPositive([1, 2, 3, 4, 5]));
- text: <code>checkPositive([-1, -2, -3, -4, -5])</code> should return <code>false</code>.
testString: assert(!checkPositive([-1, -2, -3, -4, -5]));
Your code should use the `some` method.
```js
assert(code.match(/\.some/g));
```
</section>
`checkPositive([1, 2, 3, -4, 5])` should return `true`.
## Challenge Seed
<section id='challengeSeed'>
```js
assert(checkPositive([1, 2, 3, -4, 5]));
```
<div id='js-seed'>
`checkPositive([1, 2, 3, 4, 5])` should return `true`.
```js
assert(checkPositive([1, 2, 3, 4, 5]));
```
`checkPositive([-1, -2, -3, -4, -5])` should return `false`.
```js
assert(!checkPositive([-1, -2, -3, -4, -5]));
```
# --seed--
## --seed-contents--
```js
function checkPositive(arr) {
@ -58,14 +63,7 @@ function checkPositive(arr) {
checkPositive([1, 2, 3, -4, 5]);
```
</div>
</section>
## Solution
<section id='solution'>
# --solutions--
```js
function checkPositive(arr) {
@ -75,5 +73,3 @@ function checkPositive(arr) {
}
checkPositive([1, 2, 3, -4, 5]);
```
</section>