docs: add Spanish docs
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b67
|
||||
title: Add Elements to the End of an Array Using concat Instead of push
|
||||
localeTitle: Agregue elementos al final de una matriz usando concat en lugar de empujar
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La programación funcional tiene que ver con la creación y el uso de funciones no mutantes.
|
||||
El último desafío introdujo el método <code>concat</code> como una forma de combinar arreglos en uno nuevo sin mutar los arreglos originales. Comparar <code>concat</code> con el método de <code>push</code> . <code>Push</code> agrega un elemento al final de la misma matriz a la que se llama, lo que muta esa matriz. Aquí hay un ejemplo:
|
||||
<blockquote>var arr = [1, 2, 3];<br>arr.push([4, 5, 6]);<br>// arr is changed to [1, 2, 3, [4, 5, 6]]<br>// Not the functional programming way</blockquote>
|
||||
<code>Concat</code> ofrece una forma de agregar nuevos elementos al final de una matriz sin efectos secundarios de mutación.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Cambie la función <code>nonMutatingPush</code> para que use <code>concat</code> para agregar <code>newItem</code> al final del <code>original</code> lugar de <code>push</code> . La función debe devolver una matriz.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método <code>concat</code> .
|
||||
testString: 'assert(code.match(/\.concat/g), "Your code should use the <code>concat</code> method.");'
|
||||
- text: Su código no debe utilizar el método de <code>push</code> .
|
||||
testString: 'assert(!code.match(/\.push/g), "Your code should not use the <code>push</code> method.");'
|
||||
- text: La <code>first</code> matriz no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), "The <code>first</code> array should not change.");'
|
||||
- text: La <code>second</code> matriz no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(second) === JSON.stringify([4, 5]), "The <code>second</code> array should not change.");'
|
||||
- text: ' <code>nonMutatingPush([1, 2, 3], [4, 5])</code> debe devolver <code>[1, 2, 3, 4, 5]</code> .'
|
||||
testString: 'assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), "<code>nonMutatingPush([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function nonMutatingPush(original, newItem) {
|
||||
// Add your code below this line
|
||||
return original.push(newItem);
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingPush(first, second);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6d
|
||||
title: Apply Functional Programming to Convert Strings to URL Slugs
|
||||
localeTitle: Aplique programación funcional para convertir cadenas en slugs de URL
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Los últimos varios desafíos cubrieron una serie de métodos de matriz y cadena útiles que siguen los principios de programación funcional. También hemos aprendido sobre <code>reduce</code> , que es un método poderoso que se utiliza para reducir problemas a formas más simples. Desde los promedios de computación hasta la clasificación, cualquier operación de matriz se puede lograr aplicándolo. Recordemos que el <code>map</code> y el <code>filter</code> son casos especiales de <code>reduce</code> .
|
||||
Combinemos lo que hemos aprendido para resolver un problema práctico.
|
||||
Muchos sitios de administración de contenido (CMS) tienen los títulos de una publicación agregada a parte de la URL con fines de marcadores simples. Por ejemplo, si escribe una publicación mediana titulada "Dejar de usar reducir", es probable que la URL tenga alguna forma de la cadena de título ("... / stop-using-reduce-)". Es posible que ya hayas notado esto en el sitio freeCodeCamp.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Rellene la función <code>urlSlug</code> para que convierta un <code>title</code> cadena y devuelva la versión con guión para la URL. Puede usar cualquiera de los métodos cubiertos en esta sección, y no usar <code>replace</code> . Estos son los requisitos:
|
||||
La entrada es una cadena con espacios y palabras en mayúsculas
|
||||
La salida es una cadena con espacios entre palabras reemplazadas por un guión ( <code>-</code> )
|
||||
La salida debe ser todas letras minúsculas
|
||||
La salida debe no tiene espacios
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>globalTitle</code> no debe cambiar.
|
||||
testString: 'assert(globalTitle === "Winter Is Coming", "The <code>globalTitle</code> variable should not change.");'
|
||||
- text: Su código no debe usar el método de <code>replace</code> para este desafío.
|
||||
testString: 'assert(!code.match(/\.replace/g), "Your code should not use the <code>replace</code> method for this challenge.");'
|
||||
- text: <code>urlSlug("Winter Is Coming")</code> debería devolver <code>"winter-is-coming"</code> .
|
||||
testString: 'assert(urlSlug("Winter Is Coming") === "winter-is-coming", "<code>urlSlug("Winter Is Coming")</code> should return <code>"winter-is-coming"</code>.");'
|
||||
- text: <code>urlSlug(" Winter Is Coming")</code> debería devolver <code>"winter-is-coming"</code> .
|
||||
testString: 'assert(urlSlug(" Winter Is Coming") === "winter-is-coming", "<code>urlSlug(" Winter Is Coming")</code> should return <code>"winter-is-coming"</code>.");'
|
||||
- text: <code>urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")</code> <code>"a-mind-needs-books-like-a-sword-needs-a-whetstone"</code> <code>urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone")</code> debería devolver <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", "<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>.");'
|
||||
- text: <code>urlSlug("Hold The Door")</code> debe devolver <code>"hold-the-door"</code> .
|
||||
testString: 'assert(urlSlug("Hold The Door") === "hold-the-door", "<code>urlSlug("Hold The Door")</code> should return <code>"hold-the-door"</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var globalTitle = "Winter Is Coming";
|
||||
|
||||
// Add your code below this line
|
||||
function urlSlug(title) {
|
||||
|
||||
|
||||
}
|
||||
// Add your code above this line
|
||||
|
||||
var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5e
|
||||
title: Avoid Mutations and Side Effects Using Functional Programming
|
||||
localeTitle: Evite las mutaciones y los efectos secundarios utilizando la programación funcional
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Si aún no lo ha resuelto, el problema en el desafío anterior fue con la llamada de <code>splice</code> en la función <code>tabClose()</code> . Desafortunadamente, el <code>splice</code> cambia la matriz original a la que se llama, por lo que la segunda llamada a esta usó una matriz modificada y dio resultados inesperados.
|
||||
Este es un pequeño ejemplo de un patrón mucho más grande: se llama una función en una variable, una matriz o un objeto, y la función cambia la variable o algo en el objeto.
|
||||
Uno de los principios básicos de la programación funcional es no cambiar las cosas. Los cambios conducen a errores. Es más fácil prevenir errores sabiendo que sus funciones no cambian nada, incluidos los argumentos de la función o cualquier variable global.
|
||||
El ejemplo anterior no tuvo operaciones complicadas, pero el método de <code>splice</code> cambió la matriz original y dio como resultado un error.
|
||||
Recuerde que en la programación funcional, cambiar o alterar las cosas se denomina <code>mutation</code> , y el resultado se denomina <code>side effect</code> . Una función, idealmente, debería ser una <code>pure function</code> , lo que significa que no causa ningún efecto secundario.
|
||||
Intentemos dominar esta disciplina y no alteremos ninguna variable u objeto en nuestro código.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Rellene el código del <code>incrementer</code> función para que devuelva el valor de la variable global <code>fixedValue</code> incrementado en uno.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su <code>incrementer</code> funciones no debe cambiar el valor de <code>fixedValue</code> .
|
||||
testString: 'assert(fixedValue === 4, "Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.");'
|
||||
- text: Su función <code>incrementer</code> debe devolver un valor que sea mayor que el valor de valor <code>fixedValue</code> .
|
||||
testString: 'assert(newValue === 5, "Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
function incrementer () {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
|
||||
var newValue = incrementer(); // Should equal 5
|
||||
console.log(fixedValue); // Should print 4
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6c
|
||||
title: Combine an Array into a String Using the join Method
|
||||
localeTitle: Combina una matriz en una cadena usando el método de unión
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El método de <code>join</code> se utiliza para unir los elementos de una matriz para crear una cadena. Toma un argumento para el delimitador que se usa para separar los elementos de la matriz en la cadena.
|
||||
Aquí hay un ejemplo:
|
||||
<blockquote>var arr = ["Hello", "World"];<br>var str = arr.join(" ");<br>// Sets str to "Hello World"</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use el método de <code>join</code> (entre otros) dentro de la función de <code>sentensify</code> para hacer una oración de las palabras en la cadena <code>str</code> . La función debe devolver una cadena. Por ejemplo, "I-like-Star-Wars" se convertiría a "Me gusta Star Wars". Para este desafío, no utilice el método de <code>replace</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>join</code> .
|
||||
testString: 'assert(code.match(/\.join/g), "Your code should use the <code>join</code> method.");'
|
||||
- text: Su código no debe utilizar el método de <code>replace</code> .
|
||||
testString: 'assert(!code.match(/\.replace/g), "Your code should not use the <code>replace</code> method.");'
|
||||
- text: <code>sentensify("May-the-force-be-with-you")</code> debe devolver una cadena.
|
||||
testString: 'assert(typeof sentensify("May-the-force-be-with-you") === "string", "<code>sentensify("May-the-force-be-with-you")</code> should return a string.");'
|
||||
- text: <code>sentensify("May-the-force-be-with-you")</code> debe devolver <code>"May the force be with you"</code> .
|
||||
testString: 'assert(sentensify("May-the-force-be-with-you") === "May the force be with you", "<code>sentensify("May-the-force-be-with-you")</code> should return <code>"May the force be with you"</code>.");'
|
||||
- text: <code>sentensify("The.force.is.strong.with.this.one")</code> debe devolver <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", "<code>sentensify("The.force.is.strong.with.this.one")</code> should return <code>"The force is strong with this one"</code>.");'
|
||||
- text: ' <code>sentensify("There,has,been,an,awakening")</code> debería regresar <code>"There has been an awakening"</code> .
|
||||
testString: 'assert(sentensify("There,has,been,an,awakening") === "There has been an awakening", "<code>sentensify("There,has,been,an,awakening")</code> should return <code>"There has been an awakening"</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function sentensify(str) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
sentensify("May-the-force-be-with-you");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b66
|
||||
title: Combine Two Arrays Using the concat Method
|
||||
localeTitle: Combina dos matrices usando el método concat
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<code>Concatenation</code> significa unir elementos de extremo a extremo. JavaScript ofrece el método <code>concat</code> para cadenas y matrices que funcionan de la misma manera. Para las matrices, el método se llama en una, luego se proporciona otra matriz como el argumento a <code>concat</code> , que se agrega al final de la primera matriz. Devuelve una nueva matriz y no muta ninguna de las matrices originales. Aquí hay un ejemplo:
|
||||
<blockquote>[1, 2, 3].concat([4, 5, 6]);<br>// Returns a new array [1, 2, 3, 4, 5, 6]</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Utilice el método <code>concat</code> en la función <code>nonMutatingConcat</code> para concatenar <code>attach</code> al final del <code>original</code> . La función debe devolver la matriz concatenada.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método <code>concat</code> .
|
||||
testString: 'assert(code.match(/\.concat/g), "Your code should use the <code>concat</code> method.");'
|
||||
- text: La <code>first</code> matriz no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), "The <code>first</code> array should not change.");'
|
||||
- text: La <code>second</code> matriz no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(second) === JSON.stringify([4, 5]), "The <code>second</code> array should not change.");'
|
||||
- text: ' <code>nonMutatingConcat([1, 2, 3], [4, 5])</code> debe devolver <code>[1, 2, 3, 4, 5]</code> .'
|
||||
testString: 'assert(JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), "<code>nonMutatingConcat([1, 2, 3], [4, 5])</code> should return <code>[1, 2, 3, 4, 5]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function nonMutatingConcat(original, attach) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
var first = [1, 2, 3];
|
||||
var second = [4, 5];
|
||||
nonMutatingConcat(first, second);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b62
|
||||
title: Implement map on a Prototype
|
||||
localeTitle: Implementar mapa en un prototipo
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Como ha visto al aplicar <code>Array.prototype.map()</code> , o simplemente <code>map()</code> anteriormente, el método de <code>map</code> devuelve una matriz de la misma longitud que la que se solicitó. Tampoco altera la matriz original, siempre que su función de devolución de llamada no lo haga.
|
||||
En otras palabras, el <code>map</code> es una función pura, y su salida depende únicamente de sus entradas. Además, toma otra función como argumento.
|
||||
Nos enseñaría mucho sobre el <code>map</code> para intentar implementar una versión que se comporte exactamente como <code>Array.prototype.map()</code> con un bucle <code>for</code> o <code>Array.prototype.forEach()</code> .
|
||||
Nota: Una función pura puede alterar las variables locales definidas dentro de su alcance, aunque es preferible evitar eso también.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Escriba su propio <code>Array.prototype.myMap()</code> , que debería comportarse exactamente como <code>Array.prototype.map()</code> . Puedes usar un bucle <code>for</code> o el método <code>forEach</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>new_s</code> debe ser igual a <code>[46, 130, 196, 10]</code> .'
|
||||
testString: 'assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]), "<code>new_s</code> should equal <code>[46, 130, 196, 10]</code>.");'
|
||||
- text: Su código no debe utilizar el método de <code>map</code> .
|
||||
testString: 'assert(!code.match(/\.map/g), "Your code should not use the <code>map</code> method.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myMap = function(callback){
|
||||
var newArray = [];
|
||||
// Add your code below this line
|
||||
|
||||
// Add your code above this line
|
||||
return newArray;
|
||||
|
||||
};
|
||||
|
||||
var new_s = s.myMap(function(item){
|
||||
return item * 2;
|
||||
});
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b64
|
||||
title: Implement the filter Method on a Prototype
|
||||
localeTitle: Implementar el método de filtro en un prototipo
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Nos enseñaría mucho sobre el método de <code>filter</code> si intentáramos implementar una versión que se comporte exactamente como <code>Array.prototype.filter()</code> . Puede usar un bucle <code>for</code> o <code>Array.prototype.forEach()</code> .
|
||||
Nota: Una función pura puede alterar las variables locales definidas dentro de su alcance, aunque es preferible evitar eso también.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Escriba su propio <code>Array.prototype.myFilter()</code> , que debe comportarse exactamente como <code>Array.prototype.filter()</code> . Puede usar un bucle <code>for</code> o el método <code>Array.prototype.forEach()</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>new_s</code> debe ser igual a <code>[23, 65, 5]</code> .'
|
||||
testString: 'assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]), "<code>new_s</code> should equal <code>[23, 65, 5]</code>.");'
|
||||
- text: Su código no debe utilizar el método de <code>filter</code> .
|
||||
testString: 'assert(!code.match(/\.filter/g), "Your code should not use the <code>filter</code> method.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global Array
|
||||
var s = [23, 65, 98, 5];
|
||||
|
||||
Array.prototype.myFilter = function(callback){
|
||||
var newArray = [];
|
||||
// Add your code below this line
|
||||
|
||||
// Add your code above this line
|
||||
return newArray;
|
||||
|
||||
};
|
||||
|
||||
var new_s = s.myFilter(function(item){
|
||||
return item % 2 === 1;
|
||||
});
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b70
|
||||
title: Introduction to Currying and Partial Application
|
||||
localeTitle: Introducción al curry y aplicación parcial.
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La <code>arity</code> de una función es el número de argumentos que requiere. <code>Currying</code> una función significa convertir una función de N <code>arity</code> en N funciones de <code>arity</code> 1.
|
||||
En otras palabras, reestructura una función para que tome un argumento, luego devuelva otra función que tome el siguiente argumento, y así sucesivamente.
|
||||
Aquí hay un ejemplo:
|
||||
<blockquote>//Un-curried function<br>function unCurried(x, y) {<br> return x + y;<br>}<br><br>//Curried function<br>function curried(x) {<br> return function(y) {<br> return x + y;<br> }<br>}<br>curried(1)(2) // Returns 3</blockquote>
|
||||
Esto es útil en su programa si no puede suministrar todos los argumentos a una función al mismo tiempo. Puede guardar cada llamada de función en una variable, que mantendrá la referencia de función devuelta que toma el siguiente argumento cuando esté disponible. Aquí hay un ejemplo que usa la función <code>curried</code> en el ejemplo anterior:
|
||||
<blockquote>// Call a curried function in parts:<br>var funcForY = curried(1);<br>console.log(funcForY(2)); // Prints 3</blockquote>
|
||||
De manera similar, <code>partial application</code> puede describirse como la aplicación de algunos argumentos a una función a la vez y la devolución de otra función que se aplica a más argumentos.
|
||||
Aquí hay un ejemplo:
|
||||
<blockquote>//Impartial function<br>function impartial(x, y, z) {<br> return x + y + z;<br>}<br>var partialFn = impartial.bind(this, 1, 2);<br>partialFn(10); // Returns 13</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Rellene el cuerpo de la función de <code>add</code> para que use el curry para agregar los parámetros <code>x</code> , <code>y</code> y <code>z</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: <code>add(10)(20)(30)</code> debe devolver <code>60</code> .
|
||||
testString: 'assert(add(10)(20)(30) === 60, "<code>add(10)(20)(30)</code> should return <code>60</code>.");'
|
||||
- text: <code>add(1)(2)(3)</code> debe devolver <code>6</code> .
|
||||
testString: 'assert(add(1)(2)(3) === 6, "<code>add(1)(2)(3)</code> should return <code>6</code>.");'
|
||||
- text: <code>add(11)(22)(33)</code> debe devolver <code>66</code> .
|
||||
testString: 'assert(add(11)(22)(33) === 66, "<code>add(11)(22)(33)</code> should return <code>66</code>.");'
|
||||
- text: Su código debe incluir una declaración final que devuelva <code>x + y + z</code> .
|
||||
testString: 'assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g), "Your code should include a final statement that returns <code>x + y + z</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function add(x) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
add(10)(20)(30);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,87 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b5b
|
||||
title: Learn About Functional Programming
|
||||
localeTitle: Aprenda acerca de la programación funcional
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La programación funcional es un estilo de programación donde las soluciones son funciones simples y aisladas, sin efectos secundarios fuera del alcance de la función.
|
||||
<code>INPUT -> PROCESS -> OUTPUT</code>
|
||||
La programación funcional se trata de:
|
||||
1) Funciones aisladas: no hay dependencia del estado del programa, que incluye variables globales que están sujetas a cambios
|
||||
2) Funciones puras: la misma entrada siempre da el mismo resultado
|
||||
3) Las funciones con efectos secundarios limitados: cualquier cambio o mutación en el estado del programa fuera de la función se controlan cuidadosamente
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
A los miembros de freeCodeCamp les encanta el té.
|
||||
En el editor de código, las funciones <code>prepareTea</code> y <code>getTea</code> ya están definidas para usted. Llame a la función <code>getTea</code> para obtener 40 tazas de té para el equipo y guárdelas en la variable <code>tea4TeamFCC</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>tea4TeamFCC</code> debe contener 40 tazas de té para el equipo.
|
||||
testString: 'assert(tea4TeamFCC.length === 40, "The <code>tea4TeamFCC</code> variable should hold 40 cups of tea for the team.");'
|
||||
- text: La variable <code>tea4TeamFCC</code> debe contener tazas de té verde.
|
||||
testString: 'assert(tea4TeamFCC[0] === "greenTea", "The <code>tea4TeamFCC</code> variable should hold cups of green tea.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
/**
|
||||
* A long process to prepare tea.
|
||||
* @return {string} A cup of tea.
|
||||
**/
|
||||
const prepareTea = () => 'greenTea';
|
||||
|
||||
/**
|
||||
* Get given number of cups of tea.
|
||||
* @param {number} numOfCups Number of required cups of tea.
|
||||
* @return {Array<string>} Given amount of tea cups.
|
||||
**/
|
||||
const getTea = (numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Add your code below this line
|
||||
|
||||
const tea4TeamFCC = null; // :(
|
||||
|
||||
// Add your code above this line
|
||||
|
||||
console.log(tea4TeamFCC);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5f
|
||||
title: Pass Arguments to Avoid External Dependence in a Function
|
||||
localeTitle: Pasar argumentos para evitar la dependencia externa en una función
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El último desafío fue un paso más cerca de los principios de programación funcional, pero todavía falta algo.
|
||||
No alteramos el valor de la variable global, pero el <code>incrementer</code> la función no funcionaría sin que la variable global <code>fixedValue</code> estuviera allí.
|
||||
Otro principio de la programación funcional es siempre declarar explícitamente sus dependencias. Esto significa que si una función depende de que una variable u objeto esté presente, entonces pase esa variable u objeto directamente a la función como un argumento.
|
||||
Hay varias buenas consecuencias de este principio. La función es más fácil de probar, usted sabe exactamente qué entrada toma, y no dependerá de nada más en su programa.
|
||||
Esto le puede dar más confianza cuando modifica, elimina o agrega un nuevo código. Sabría lo que puede o no puede cambiar y puede ver dónde están las posibles trampas.
|
||||
Finalmente, la función siempre produciría la misma salida para el mismo conjunto de entradas, sin importar qué parte del código la ejecute.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Actualicemos la función <code>incrementer</code> para declarar claramente sus dependencias.
|
||||
Escriba la función <code>incrementer</code> para que tome un argumento y luego aumente el valor en uno.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su <code>incrementer</code> funciones no debe cambiar el valor de <code>fixedValue</code> .
|
||||
testString: 'assert(fixedValue === 4, "Your function <code>incrementer</code> should not change the value of <code>fixedValue</code>.");'
|
||||
- text: Su función <code>incrementer</code> debe tomar un parámetro.
|
||||
testString: 'assert(code.match(/function\s+?incrementer\s*?\(.+?\)/g), "Your <code>incrementer</code> function should take a parameter.");'
|
||||
- text: Su función <code>incrementer</code> debe devolver un valor que sea mayor que el valor de valor <code>fixedValue</code> .
|
||||
testString: 'assert(newValue === 5, "Your <code>incrementer</code> function should return a value that is one larger than the <code>fixedValue</code> value.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var fixedValue = 4;
|
||||
|
||||
// Add your code below this line
|
||||
function incrementer () {
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
|
||||
var newValue = incrementer(fixedValue); // Should equal 5
|
||||
console.log(fixedValue); // Should print 4
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,91 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b60
|
||||
title: Refactor Global Variables Out of Functions
|
||||
localeTitle: Refactorizar variables globales fuera de funciones
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Hasta ahora, hemos visto dos principios distintos para la programación funcional:
|
||||
1) No alterar una variable u objeto: cree nuevas variables y objetos y devuélvalos si es necesario desde una función.
|
||||
2) Declare los argumentos de la función: cualquier cálculo dentro de una función depende solo de los argumentos, y no de cualquier objeto global o variable.
|
||||
Agregar uno a un número no es muy emocionante, pero podemos aplicar estos principios al trabajar con matrices u objetos más complejos.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Refactorice (reescriba) el código para que la matriz de <code>bookList</code> global no se <code>bookList</code> dentro de ninguna de las funciones. La función de <code>add</code> debería agregar el <code>bookName</code> de <code>bookName</code> dado al final de una matriz. La función de <code>remove</code> debe eliminar el <code>bookName</code> de <code>bookName</code> dado de una matriz. Ambas funciones deben devolver una matriz, y cualquier parámetro nuevo debe agregarse antes del <code>bookName</code> one.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: ' <code>bookList</code> no debe cambiar y aún debe ser igual a <code>["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]</code> .'
|
||||
testString: 'assert(JSON.stringify(bookList) === JSON.stringify(["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]), "<code>bookList</code> should not change and still equal <code>["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]</code>.");'
|
||||
- text: ' <code>newBookList</code> debería ser igual a <code>["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]</code> .'
|
||||
testString: 'assert(JSON.stringify(newBookList) === JSON.stringify(["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]), "<code>newBookList</code> should equal <code>["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]</code>.");'
|
||||
- text: ' <code>newerBookList</code> debería ser igual a <code>["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]</code> .'
|
||||
testString: 'assert(JSON.stringify(newerBookList) === JSON.stringify(["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]), "<code>newerBookList</code> should equal <code>["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]</code>.");'
|
||||
- text: ' <code>newestBookList</code> debería ser igual a <code>["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]</code> .
|
||||
testString: 'assert(JSON.stringify(newestBookList) === JSON.stringify(["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]), "<code>newestBookList</code> should equal <code>["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
|
||||
|
||||
/* This function should add a book to the list and return the list */
|
||||
// New parameters should come before the bookName one
|
||||
|
||||
// Add your code below this line
|
||||
function add (bookName) {
|
||||
|
||||
return bookList.push(bookName);
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
|
||||
/* This function should remove a book from the list and return the list */
|
||||
// New parameters should come before the bookName one
|
||||
|
||||
// Add your code below this line
|
||||
function remove (bookName) {
|
||||
if (bookList.indexOf(bookName) >= 0) {
|
||||
|
||||
return bookList.splice(0, 1, bookName);
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
|
||||
console.log(bookList);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: 9d7123c8c441eeafaeb5bdef
|
||||
title: Remove Elements from an Array Using slice Instead of splice
|
||||
localeTitle: Eliminar elementos de una matriz usando una división en lugar de empalme
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Un patrón común al trabajar con matrices es cuando desea eliminar elementos y conservar el resto de la matriz. JavaScript ofrece el método de <code>splice</code> para esto, que toma argumentos para el índice de dónde comenzar a eliminar elementos, luego la cantidad de elementos que se eliminarán. Si no se proporciona el segundo argumento, el valor predeterminado es eliminar elementos hasta el final. Sin embargo, el método de <code>splice</code> muta la matriz original a la que se llama. Aquí hay un ejemplo:
|
||||
<blockquote>var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];<br>cities.splice(3, 1); // Returns "London" and deletes it from the cities array<br>// cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]</blockquote>
|
||||
Como hemos visto en el último desafío, la <code>slice</code> método no muta la matriz original, pero devuelve una nueva que se pueden guardar en una variable. Recuerde que el método de <code>slice</code> toma dos argumentos para que los índices comiencen y terminen la división (el final no es inclusivo) y devuelve esos elementos en una nueva matriz. Uso de la <code>slice</code> método en lugar de <code>splice</code> ayuda a evitar los efectos secundarios de matriz-mutación.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Reescriba la función <code>nonMutatingSplice</code> utilizando <code>slice</code> lugar de <code>splice</code> . Debe limitar la matriz de <code>cities</code> proporcionada a una longitud de 3 y devolver una nueva matriz con solo los tres primeros elementos.
|
||||
No mutar la matriz original proporcionada a la función.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>slice</code> .
|
||||
testString: 'assert(code.match(/\.slice/g), "Your code should use the <code>slice</code> method.");'
|
||||
- text: Su código no debe utilizar el método de <code>splice</code> .
|
||||
testString: 'assert(!code.match(/\.splice/g), "Your code should not use the <code>splice</code> method.");'
|
||||
- text: La matriz <code>inputCities</code> no debería cambiar.
|
||||
testString: 'assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]), "The <code>inputCities</code> array should not change.");'
|
||||
- text: ' <code>nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])</code> debe devolver <code>["Chicago", "Delhi", "Islamabad"]</code> .'
|
||||
testString: 'assert(JSON.stringify(nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])) === JSON.stringify(["Chicago", "Delhi", "Islamabad"]), "<code>nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])</code> should return <code>["Chicago", "Delhi", "Islamabad"]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function nonMutatingSplice(cities) {
|
||||
// Add your code below this line
|
||||
return cities.splice(3);
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
var inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
|
||||
nonMutatingSplice(inputCities);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,64 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b6a
|
||||
title: Return a Sorted Array Without Changing the Original Array
|
||||
localeTitle: Devuelva una matriz ordenada sin cambiar la matriz original
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Un efecto secundario del método de <code>sort</code> es que cambia el orden de los elementos en la matriz original. En otras palabras, muta la matriz en su lugar. Una forma de evitar esto es primero concatenar una matriz vacía con la ordenada (recuerde que <code>concat</code> devuelve una nueva matriz), luego ejecute el método de <code>sort</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Utilice el método de <code>sort</code> en la función <code>nonMutatingSort</code> para ordenar los elementos de una matriz en orden ascendente. La función debe devolver una nueva matriz y no mutar la variable <code>globalArray</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>sort</code> .
|
||||
testString: 'assert(code.match(/\.sort/g), "Your code should use the <code>sort</code> method.");'
|
||||
- text: Su código debe utilizar el método <code>concat</code> .
|
||||
testString: 'assert(code.match(/\.concat/g), "Your code should use the <code>concat</code> method.");'
|
||||
- text: La variable <code>globalArray</code> no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]), "The <code>globalArray</code> variable should not change.");'
|
||||
- text: ' <code>nonMutatingSort(globalArray)</code> debe devolver <code>[2, 3, 5, 6, 9]</code> .'
|
||||
testString: 'assert(JSON.stringify(nonMutatingSort(globalArray)) === JSON.stringify([2, 3, 5, 6, 9]), "<code>nonMutatingSort(globalArray)</code> should return <code>[2, 3, 5, 6, 9]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
var globalArray = [5, 6, 3, 2, 9];
|
||||
function nonMutatingSort(arr) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
nonMutatingSort(globalArray);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: 587d7b90367417b2b2512b65
|
||||
title: Return Part of an Array Using the slice Method
|
||||
localeTitle: Devolver parte de una matriz utilizando el método de corte
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El método de <code>slice</code> devuelve una copia de ciertos elementos de una matriz. Puede tomar dos argumentos, el primero proporciona el índice de dónde comenzar la división, el segundo es el índice de dónde finalizar la división (y no está incluido). Si no se proporcionan los argumentos, el valor predeterminado es comenzar desde el principio de la matriz hasta el final, lo cual es una forma fácil de hacer una copia de toda la matriz. La <code>slice</code> método no muta la matriz original, pero devuelve una nueva.
|
||||
Aquí hay un ejemplo:
|
||||
<blockquote>var arr = ["Cat", "Dog", "Tiger", "Zebra"];<br>var newArray = arr.slice(1, 3);<br>// Sets newArray to ["Dog", "Tiger"]</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Utilice la <code>slice</code> método en el <code>sliceArray</code> función para devolver parte de la <code>anim</code> matriz dada las proporcionadas <code>beginSlice</code> y <code>endSlice</code> índices. La función debe devolver una matriz.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>slice</code> .
|
||||
testString: 'assert(code.match(/\.slice/g), "Your code should use the <code>slice</code> method.");'
|
||||
- text: La variable <code>inputAnim</code> no debe cambiar.
|
||||
testString: 'assert(JSON.stringify(inputAnim) === JSON.stringify(["Cat", "Dog", "Tiger", "Zebra", "Ant"]), "The <code>inputAnim</code> variable should not change.");'
|
||||
- text: ' <code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)</code> debe devolver <code>["Dog", "Tiger"]</code> .'
|
||||
testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)) === JSON.stringify(["Dog", "Tiger"]), "<code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)</code> should return <code>["Dog", "Tiger"]</code>.");'
|
||||
- text: ' <code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)</code> debe devolver <code>["Cat"]</code> .'
|
||||
testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)) === JSON.stringify(["Cat"]), "<code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)</code> should return <code>["Cat"]</code>.");'
|
||||
- text: ' <code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)</code> debe devolver <code>["Dog", "Tiger", "Zebra"]</code> .'
|
||||
testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)) === JSON.stringify(["Dog", "Tiger", "Zebra"]), "<code>sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)</code> should return <code>["Dog", "Tiger", "Zebra"]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function sliceArray(anim, beginSlice, endSlice) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
var inputAnim = ["Cat", "Dog", "Tiger", "Zebra", "Ant"];
|
||||
sliceArray(inputAnim, 1, 3);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b69
|
||||
title: Sort an Array Alphabetically using the sort Method
|
||||
localeTitle: Ordena una matriz alfabéticamente usando el método de clasificación
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El método de <code>sort</code> ordena los elementos de una matriz de acuerdo con la función de devolución de llamada.
|
||||
Por ejemplo:
|
||||
<blockquote>function ascendingOrder(arr) {<br> return arr.sort(function(a, b) {<br> return a - b;<br> });<br>}<br>ascendingOrder([1, 5, 2, 3, 4]);<br>// Returns [1, 2, 3, 4, 5]<br><br>function reverseAlpha(arr) {<br> return arr.sort(function(a, b) {<br> return a < b;<br> });<br>}<br>reverseAlpha(['l', 'h', 'z', 'b', 's']);<br>// Returns ['z', 's', 'l', 'h', 'b']</blockquote>
|
||||
Nota: Se recomienda proporcionar una función de devolución de llamada para especificar cómo ordenar los elementos de la matriz. El método de clasificación predeterminado de JavaScript es por valor de punto Unicode de cadena, que puede devolver resultados inesperados.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Utilice el método de <code>sort</code> en la función de orden <code>alphabeticalOrder</code> para ordenar los elementos de <code>arr</code> en orden alfabético.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>sort</code> .
|
||||
testString: 'assert(code.match(/\.sort/g), "Your code should use the <code>sort</code> method.");'
|
||||
- text: ' <code>alphabeticalOrder(["a", "d", "c", "a", "z", "g"])</code> debe devolver <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"]), "<code>alphabeticalOrder(["a", "d", "c", "a", "z", "g"])</code> should return <code>["a", "a", "c", "d", "g", "z"]</code>.");'
|
||||
- text: ' <code>alphabeticalOrder(["x", "h", "a", "m", "n", "m"])</code> debe devolver <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"]), "<code>alphabeticalOrder(["x", "h", "a", "m", "n", "m"])</code> should return <code>["a", "h", "m", "m", "n", "x"]</code>.");'
|
||||
- text: ' <code>alphabeticalOrder(["a", "a", "a", "a", "x", "t"])</code> debe devolver <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"]), "<code>alphabeticalOrder(["a", "a", "a", "a", "x", "t"])</code> should return <code>["a", "a", "a", "a", "t", "x"]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function alphabeticalOrder(arr) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: 587d7daa367417b2b2512b6b
|
||||
title: Split a String into an Array Using the split Method
|
||||
localeTitle: Dividir una cadena en una matriz usando el método de división
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El método de <code>split</code> divide una cadena en una matriz de cadenas. Toma un argumento para el delimitador, que puede ser un carácter que se usa para separar la cadena o una expresión regular. Por ejemplo, si el delimitador es un espacio, obtiene una matriz de palabras, y si el delimitador es una cadena vacía, obtiene una matriz de cada carácter en la cadena.
|
||||
Aquí hay dos ejemplos que dividen una cadena por espacios, luego otro por dígitos usando una expresión regular:
|
||||
<blockquote>var str = "Hello World";<br>var bySpace = str.split(" ");<br>// Sets bySpace to ["Hello", "World"]<br><br>var otherString = "How9are7you2today";<br>var byDigits = otherString.split(/\d/);<br>// Sets byDigits to ["How", "are", "you", "today"]</blockquote>
|
||||
Dado que las cadenas son inmutables, el método de <code>split</code> facilita el trabajo con ellas.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Utilice la <code>split</code> método dentro de la <code>splitify</code> función de dividir <code>str</code> en una matriz de palabras. La función debe devolver la matriz. Tenga en cuenta que las palabras no siempre están separadas por espacios y que la matriz no debe contener puntuación.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar el método de <code>split</code> .
|
||||
testString: 'assert(code.match(/\.split/g), "Your code should use the <code>split</code> method.");'
|
||||
- text: ' <code>splitify("Hello World,I-am code")</code> debe devolver <code>["Hello", "World", "I", "am", "code"]</code> .'
|
||||
testString: 'assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"]), "<code>splitify("Hello World,I-am code")</code> should return <code>["Hello", "World", "I", "am", "code"]</code>.");'
|
||||
- text: ' <code>splitify("Earth-is-our home")</code> debería devolver <code>["Earth", "is", "our", "home"]</code> .'
|
||||
testString: 'assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"]), "<code>splitify("Earth-is-our home")</code> should return <code>["Earth", "is", "our", "home"]</code>.");'
|
||||
- text: ' <code>splitify("This.is.a-sentence")</code> debe devolver <code>["This", "is", "a", "sentence"]</code> .'
|
||||
testString: 'assert(JSON.stringify(splitify("This.is.a-sentence")) === JSON.stringify(["This", "is", "a", "sentence"]), "<code>splitify("This.is.a-sentence")</code> should return <code>["This", "is", "a", "sentence"]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function splitify(str) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
splitify("Hello World,I-am code");
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,103 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5c
|
||||
title: Understand Functional Programming Terminology
|
||||
localeTitle: Entender la terminología de programación funcional
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El equipo de la FCC tuvo un cambio de humor y ahora quiere dos tipos de té: té verde y té negro. Hecho general: los cambios de humor del cliente son bastante comunes.
|
||||
Con esa información, tendremos que revisar la función <code>getTea</code> del último desafío para manejar varias solicitudes de té. Podemos modificar <code>getTea</code> para aceptar una función como parámetro para poder cambiar el tipo de té que prepara. Esto hace que <code>getTea</code> sea más flexible y le da al programador más control cuando cambian las solicitudes de los clientes.
|
||||
Pero primero, vamos a cubrir algunos términos funcionales:
|
||||
<code>Callbacks</code> son las funciones que se deslizan o pasan a otra función para decidir la invocación de esa función. Es posible que los haya visto pasar a otros métodos, por ejemplo, en el <code>filter</code> , la función de devolución de llamada le dice a JavaScript los criterios sobre cómo filtrar una matriz.
|
||||
funciones que pueden asignarse a una variable, pasarse a otra función o devolverse desde otra función como cualquier otro valor normal, se denominan funciones de <code>first class</code> . En JavaScript, todas las funciones son funciones de <code>first class</code> .
|
||||
Las funciones que toman una función como argumento o que devuelven una función como valor de retorno se denominan funciones de <code>higher order</code> .
|
||||
Cuando las funciones se pasan a otra función o se devuelven desde otra función, las funciones que se pasan o devuelven pueden llamarse <code>lambda</code> .
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Prepare 27 tazas de té verde y 13 tazas de té negro y almacénelas en las variables <code>tea4GreenTeamFCC</code> y <code>tea4BlackTeamFCC</code> , respectivamente. Tenga en cuenta que la función <code>getTea</code> se ha modificado, por lo que ahora toma una función como primer argumento.
|
||||
Nota: Los datos (el número de tazas de té) se proporcionan como el último argumento. Discutiremos esto más en lecciones posteriores.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>tea4GreenTeamFCC</code> debe contener 27 tazas de té verde para el equipo.
|
||||
testString: 'assert(tea4GreenTeamFCC.length === 27, "The <code>tea4GreenTeamFCC</code> variable should hold 27 cups of green tea for the team.");'
|
||||
- text: La variable <code>tea4GreenTeamFCC</code> debe contener tazas de té verde.
|
||||
testString: 'assert(tea4GreenTeamFCC[0] === "greenTea", "The <code>tea4GreenTeamFCC</code> variable should hold cups of green tea.");'
|
||||
- text: La variable <code>tea4BlackTeamFCC</code> debe contener 13 tazas de té negro.
|
||||
testString: 'assert(tea4BlackTeamFCC.length === 13, "The <code>tea4BlackTeamFCC</code> variable should hold 13 cups of black tea.");'
|
||||
- text: La variable <code>tea4BlackTeamFCC</code> debe contener tazas de té negro.
|
||||
testString: 'assert(tea4BlackTeamFCC[0] === "blackTea", "The <code>tea4BlackTeamFCC</code> variable should hold cups of black tea.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
/**
|
||||
* A long process to prepare green tea.
|
||||
* @return {string} A cup of green tea.
|
||||
**/
|
||||
const prepareGreenTea = () => 'greenTea';
|
||||
|
||||
/**
|
||||
* A long process to prepare black tea.
|
||||
* @return {string} A cup of black tea.
|
||||
**/
|
||||
const prepareBlackTea = () => 'blackTea';
|
||||
|
||||
/**
|
||||
* Get given number of cups of tea.
|
||||
* @param {function():string} prepareTea The type of tea preparing function.
|
||||
* @param {number} numOfCups Number of required cups of tea.
|
||||
* @return {Array<string>} Given amount of tea cups.
|
||||
**/
|
||||
const getTea = (prepareTea, numOfCups) => {
|
||||
const teaCups = [];
|
||||
|
||||
for(let cups = 1; cups <= numOfCups; cups += 1) {
|
||||
const teaCup = prepareTea();
|
||||
teaCups.push(teaCup);
|
||||
}
|
||||
|
||||
return teaCups;
|
||||
};
|
||||
|
||||
// Add your code below this line
|
||||
|
||||
const tea4GreenTeamFCC = null; // :(
|
||||
const tea4BlackTeamFCC = null; // :(
|
||||
|
||||
// Add your code above this line
|
||||
|
||||
console.log(
|
||||
tea4GreenTeamFCC,
|
||||
tea4BlackTeamFCC
|
||||
);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,98 @@
|
||||
---
|
||||
id: 587d7b8e367417b2b2512b5d
|
||||
title: Understand the Hazards of Using Imperative Code
|
||||
localeTitle: Entender los peligros de usar el código imperativo
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
La programación funcional es un buen hábito. Mantiene tu código fácil de administrar y te salva de errores furtivos. Pero antes de que lleguemos allí, veamos un enfoque imperativo de la programación para resaltar dónde puede tener problemas.
|
||||
En inglés (y en muchos otros idiomas), el tiempo imperativo se usa para dar comandos. De manera similar, un estilo imperativo en la programación es uno que le da a la computadora un conjunto de declaraciones para realizar una tarea.
|
||||
A menudo, las declaraciones cambian el estado del programa, como la actualización de variables globales. Un ejemplo clásico es escribir un bucle <code>for</code> que da instrucciones exactas para iterar sobre los índices de una matriz.
|
||||
En contraste, la programación funcional es una forma de programación declarativa. Usted le dice a la computadora lo que quiere hacer llamando a un método o función.
|
||||
JavaScript ofrece muchos métodos predefinidos que manejan tareas comunes, por lo que no necesita escribir cómo la computadora debe realizarlos. Por ejemplo, en lugar de utilizar el bucle <code>for</code> mencionado anteriormente, puede llamar al método de <code>map</code> que maneja los detalles de la iteración en una matriz. Esto ayuda a evitar errores semánticos, como los "Errores Off By One" que se cubrieron en la sección de Depuración.
|
||||
Considere el escenario: está navegando por la web en su navegador y desea rastrear las pestañas que ha abierto. Intentemos modelar esto usando un código simple orientado a objetos.
|
||||
Un objeto de ventana se compone de pestañas, y normalmente tiene más de una ventana abierta. Los títulos de cada sitio abierto en cada objeto de Ventana se mantienen en una matriz. Después de trabajar en el navegador (abrir nuevas pestañas, fusionar ventanas y cerrar pestañas), desea imprimir las pestañas que aún están abiertas. Las pestañas cerradas se eliminan de la matriz y las nuevas pestañas (para simplificar) se agregan al final de la misma.
|
||||
El editor de código muestra una implementación de esta funcionalidad con funciones para <code>tabOpen()</code> , <code>tabClose()</code> y <code>join()</code> . Las <code>tabs</code> matriz forman parte del objeto Window que almacena el nombre de las páginas abiertas.
|
||||
<h4> Instrucciones <h4>
|
||||
Ejecutar el código en el editor. Está utilizando un método que tiene efectos secundarios en el programa, lo que provoca un resultado incorrecto. La lista final de pestañas abiertas debe ser <code>['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']</code> pero la salida será ligeramente diferente.
|
||||
Revise el código y vea si puede resolver el problema, luego avance al próximo desafío para obtener más información.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Avanza para entender el error.
|
||||
testString: 'assert(true, "Move ahead to understand the error.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// tabs is an array of titles of each site open within the window
|
||||
var Window = function(tabs) {
|
||||
this.tabs = tabs; // we keep a record of the array inside the object
|
||||
};
|
||||
|
||||
// When you join two windows into one window
|
||||
Window.prototype.join = function (otherWindow) {
|
||||
this.tabs = this.tabs.concat(otherWindow.tabs);
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you open a new tab at the end
|
||||
Window.prototype.tabOpen = function (tab) {
|
||||
this.tabs.push('new tab'); // let's open a new tab for now
|
||||
return this;
|
||||
};
|
||||
|
||||
// When you close a tab
|
||||
Window.prototype.tabClose = function (index) {
|
||||
var tabsBeforeIndex = this.tabs.splice(0, index); // get the tabs before the tab
|
||||
var tabsAfterIndex = this.tabs.splice(index); // get the tabs after the tab
|
||||
|
||||
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together
|
||||
return this;
|
||||
};
|
||||
|
||||
// Let's create three browser windows
|
||||
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
|
||||
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
|
||||
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
|
||||
|
||||
// Now perform the tab opening, closing, and other operations
|
||||
var finalTabs = socialWindow
|
||||
.tabOpen() // Open a new tab for cat memes
|
||||
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
|
||||
.join(workWindow.tabClose(1).tabOpen());
|
||||
|
||||
alert(finalTabs.tabs);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6e
|
||||
title: Use the every Method to Check that Every Element in an Array Meets a Criteria
|
||||
localeTitle: Use cada método para verificar que cada elemento de una matriz cumple con los criterios
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<code>every</code> métodos funcionan con matrices para verificar si <em>cada</em> elemento pasa una prueba en particular. Devuelve un valor booleano: <code>true</code> si todos los valores cumplen los criterios, <code>false</code> si no.
|
||||
Por ejemplo, el siguiente código verificará si cada elemento de la matriz de <code>numbers</code> es menor que 10:
|
||||
<blockquote>var numbers = [1, 5, 8, 0, 10, 11];<br>numbers.every(function(currentValue) {<br> return currentValue < 10;<br>});<br>// Returns false</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use <code>every</code> método dentro de la función <code>checkPositive</code> para verificar si cada elemento en <code>arr</code> es positivo. La función debe devolver un valor booleano.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar <code>every</code> métodos.
|
||||
testString: 'assert(code.match(/\.every/g), "Your code should use the <code>every</code> method.");'
|
||||
- text: ' <code>checkPositive([1, 2, 3, -4, 5])</code> debe devolver <code>false</code> .'
|
||||
testString: 'assert(!checkPositive([1, 2, 3, -4, 5]), "<code>checkPositive([1, 2, 3, -4, 5])</code> should return <code>false</code>.");'
|
||||
- text: ' <code>checkPositive([1, 2, 3, 4, 5])</code> debe devolver <code>true</code> .'
|
||||
testString: 'assert(checkPositive([1, 2, 3, 4, 5]), "<code>checkPositive([1, 2, 3, 4, 5])</code> should return <code>true</code>.");'
|
||||
- text: ' <code>checkPositive([1, -2, 3, -4, 5])</code> debe devolver <code>false</code> .'
|
||||
testString: 'assert(!checkPositive([1, -2, 3, -4, 5]), "<code>checkPositive([1, -2, 3, -4, 5])</code> should return <code>false</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,178 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b63
|
||||
title: Use the filter Method to Extract Data from an Array
|
||||
localeTitle: Utilice el método de filtro para extraer datos de una matriz
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Otra función de matriz útil es <code>Array.prototype.filter()</code> , o simplemente <code>filter()</code> . El método de <code>filter</code> devuelve una nueva matriz que es a lo sumo tan larga como la matriz original, pero generalmente tiene menos elementos.
|
||||
<code>Filter</code> no altera la matriz original, al igual que el <code>map</code> . Toma una función de devolución de llamada que aplica la lógica dentro de la devolución de llamada en cada elemento de la matriz. Si un elemento devuelve verdadero según los criterios en la función de devolución de llamada, entonces se incluye en la nueva matriz.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
La variable <code>watchList</code> contiene una serie de objetos con información sobre varias películas. Use una combinación de <code>filter</code> y <code>map</code> para devolver una nueva matriz de objetos con solo <code>title</code> y claves de <code>rating</code> , pero donde <code>imdbRating</code> es mayor o igual a 8.0. Tenga en cuenta que los valores de calificación se guardan como cadenas en el objeto y es posible que desee convertirlos en números para realizar operaciones matemáticas en ellos.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>watchList</code> no debe cambiar.
|
||||
testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The <code>watchList</code> variable should not change.");'
|
||||
- text: Su código debe utilizar el método de <code>filter</code> .
|
||||
testString: 'assert(code.match(/\.filter/g), "Your code should use the <code>filter</code> method.");'
|
||||
- text: Su código no debe utilizar un bucle <code>for</code> .
|
||||
testString: 'assert(!code.match(/for\s*?\(.+?\)/g), "Your code should not use a <code>for</code> loop.");'
|
||||
- text: ' <code>filteredList</code> debe ser igual a <code>[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]</code> . '
|
||||
testString: 'assert.deepEqual(filteredList, [{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}], "<code>filteredList</code> should equal <code>[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
// Add your code below this line
|
||||
|
||||
var filteredList;
|
||||
|
||||
// Add your code above this line
|
||||
|
||||
console.log(filteredList);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,184 @@
|
||||
---
|
||||
id: 587d7b8f367417b2b2512b61
|
||||
title: Use the map Method to Extract Data from an Array
|
||||
localeTitle: Utilice el método de mapa para extraer datos de una matriz
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
Hasta ahora hemos aprendido a usar funciones puras para evitar efectos secundarios en un programa. Además, hemos visto que el valor de tener una función solo depende de sus argumentos de entrada.
|
||||
Esto es solo el comienzo. Como su nombre lo indica, la programación funcional se centra en una teoría de funciones.
|
||||
Tendría sentido poder pasarlos como argumentos a otras funciones y devolver una función desde otra función. Las funciones se consideran <code>First Class Objects</code> en JavaScript, lo que significa que se pueden usar como cualquier otro objeto. Pueden guardarse en variables, almacenarse en un objeto o pasarse como argumentos de función.
|
||||
Comencemos con algunas funciones de matriz simples, que son métodos en el prototipo de objeto de matriz. En este ejercicio estamos viendo <code>Array.prototype.map()</code> , o más simplemente un <code>map</code> .
|
||||
Recuerde que el método de <code>map</code> es una forma de iterar sobre cada elemento en una matriz. Crea una nueva matriz (sin cambiar la original) después de aplicar una función de devolución de llamada a cada elemento.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
La matriz <code>watchList</code> contiene objetos con información sobre varias películas. Use el <code>map</code> para extraer el título y la clasificación de la <code>watchList</code> de <code>watchList</code> y guarde la nueva matriz en la variable de <code>rating</code> . El código en el editor actualmente usa un bucle <code>for</code> para hacer esto, reemplaza la funcionalidad de bucle con tu expresión de <code>map</code> .
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>watchList</code> no debe cambiar.
|
||||
testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The <code>watchList</code> variable should not change.");'
|
||||
- text: Su código no debe utilizar un bucle <code>for</code> .
|
||||
testString: 'assert(!code.match(/for\s*?\(.+?\)/g), "Your code should not use a <code>for</code> loop.");'
|
||||
- text: Su código debe utilizar el método de <code>map</code> .
|
||||
testString: 'assert(code.match(/\.map/g), "Your code should use the <code>map</code> method.");'
|
||||
- text: La <code>rating</code> debería ser igual a <code>[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]</code> . '
|
||||
testString: 'assert(JSON.stringify(rating) === JSON.stringify([{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]), "<code>rating</code> should equal <code>[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
// Add your code below this line
|
||||
|
||||
var rating = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
rating.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
// Add your code above this line
|
||||
|
||||
console.log(rating);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,180 @@
|
||||
---
|
||||
id: 587d7da9367417b2b2512b68
|
||||
title: Use the reduce Method to Analyze Data
|
||||
localeTitle: Utilice el método de reducción para analizar datos
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
<code>Array.prototype.reduce()</code> , o simplemente <code>reduce()</code> , es la más general de todas las operaciones de matriz en JavaScript. Puede resolver casi cualquier problema de procesamiento de matrices utilizando el método de <code>reduce</code> .
|
||||
Este no es el caso con los métodos de <code>filter</code> y <code>map</code> , ya que no permiten la interacción entre dos elementos diferentes de la matriz. Por ejemplo, si desea comparar elementos de la matriz, o agregarlos juntos, el <code>filter</code> o el <code>map</code> no podrían procesarlo.
|
||||
El método de <code>reduce</code> permite formas más generales de procesamiento de matrices, y es posible mostrar que tanto el <code>filter</code> como el <code>map</code> pueden derivarse como una aplicación especial de <code>reduce</code> .
|
||||
Sin embargo, antes de que lleguemos allí, practiquemos <code>reduce</code> primero.
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
La variable <code>watchList</code> contiene una serie de objetos con información sobre varias películas. Use <code>reduce</code> para encontrar la calificación promedio de IMDB de las películas <strong>dirigidas por Christopher Nolan</strong> . Recuerde de los desafíos anteriores cómo <code>filter</code> datos y <code>map</code> para obtener lo que necesita. Es posible que deba crear otras variables, pero guardar el promedio final en la variable <code>averageRating</code> . Tenga en cuenta que los valores de calificación se guardan como cadenas en el objeto y deben convertirse en números antes de que se utilicen en cualquier operación matemática.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: La variable <code>watchList</code> no debe cambiar.
|
||||
testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The <code>watchList</code> variable should not change.");'
|
||||
- text: Su código debe utilizar el método de <code>reduce</code> .
|
||||
testString: 'assert(code.match(/\.reduce/g), "Your code should use the <code>reduce</code> method.");'
|
||||
- text: La <code>averageRating</code> debe ser igual a 8.675.
|
||||
testString: 'assert(averageRating == 8.675, "The <code>averageRating</code> should equal 8.675.");'
|
||||
- text: Su código no debe utilizar un bucle <code>for</code> .
|
||||
testString: 'assert(!code.match(/for\s*?\(.*\)/g), "Your code should not use a <code>for</code> loop.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
// the global variable
|
||||
var watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
"Rated": "PG-13",
|
||||
"Released": "16 Jul 2010",
|
||||
"Runtime": "148 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Christopher Nolan",
|
||||
"Actors": "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy",
|
||||
"Plot": "A thief, who steals corporate secrets through use of dream-sharing technology, is given the inverse task of planting an idea into the mind of a CEO.",
|
||||
"Language": "English, Japanese, French",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 4 Oscars. Another 143 wins & 198 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.8",
|
||||
"imdbVotes": "1,446,708",
|
||||
"imdbID": "tt1375666",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Interstellar",
|
||||
"Year": "2014",
|
||||
"Rated": "PG-13",
|
||||
"Released": "07 Nov 2014",
|
||||
"Runtime": "169 min",
|
||||
"Genre": "Adventure, Drama, Sci-Fi",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan, Christopher Nolan",
|
||||
"Actors": "Ellen Burstyn, Matthew McConaughey, Mackenzie Foy, John Lithgow",
|
||||
"Plot": "A team of explorers travel through a wormhole in space in an attempt to ensure humanity's survival.",
|
||||
"Language": "English",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 1 Oscar. Another 39 wins & 132 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjIxNTU4MzY4MF5BMl5BanBnXkFtZTgwMzM4ODI3MjE@._V1_SX300.jpg",
|
||||
"Metascore": "74",
|
||||
"imdbRating": "8.6",
|
||||
"imdbVotes": "910,366",
|
||||
"imdbID": "tt0816692",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "The Dark Knight",
|
||||
"Year": "2008",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Jul 2008",
|
||||
"Runtime": "152 min",
|
||||
"Genre": "Action, Adventure, Crime",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Jonathan Nolan (screenplay), Christopher Nolan (screenplay), Christopher Nolan (story), David S. Goyer (story), Bob Kane (characters)",
|
||||
"Actors": "Christian Bale, Heath Ledger, Aaron Eckhart, Michael Caine",
|
||||
"Plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, the caped crusader must come to terms with one of the greatest psychological tests of his ability to fight injustice.",
|
||||
"Language": "English, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 2 Oscars. Another 146 wins & 142 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTMxNTMwODM0NF5BMl5BanBnXkFtZTcwODAyMTk2Mw@@._V1_SX300.jpg",
|
||||
"Metascore": "82",
|
||||
"imdbRating": "9.0",
|
||||
"imdbVotes": "1,652,832",
|
||||
"imdbID": "tt0468569",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Batman Begins",
|
||||
"Year": "2005",
|
||||
"Rated": "PG-13",
|
||||
"Released": "15 Jun 2005",
|
||||
"Runtime": "140 min",
|
||||
"Genre": "Action, Adventure",
|
||||
"Director": "Christopher Nolan",
|
||||
"Writer": "Bob Kane (characters), David S. Goyer (story), Christopher Nolan (screenplay), David S. Goyer (screenplay)",
|
||||
"Actors": "Christian Bale, Michael Caine, Liam Neeson, Katie Holmes",
|
||||
"Plot": "After training with his mentor, Batman begins his fight to free crime-ridden Gotham City from the corruption that Scarecrow and the League of Shadows have cast upon it.",
|
||||
"Language": "English, Urdu, Mandarin",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Nominated for 1 Oscar. Another 15 wins & 66 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg",
|
||||
"Metascore": "70",
|
||||
"imdbRating": "8.3",
|
||||
"imdbVotes": "972,584",
|
||||
"imdbID": "tt0372784",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
},
|
||||
{
|
||||
"Title": "Avatar",
|
||||
"Year": "2009",
|
||||
"Rated": "PG-13",
|
||||
"Released": "18 Dec 2009",
|
||||
"Runtime": "162 min",
|
||||
"Genre": "Action, Adventure, Fantasy",
|
||||
"Director": "James Cameron",
|
||||
"Writer": "James Cameron",
|
||||
"Actors": "Sam Worthington, Zoe Saldana, Sigourney Weaver, Stephen Lang",
|
||||
"Plot": "A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.",
|
||||
"Language": "English, Spanish",
|
||||
"Country": "USA, UK",
|
||||
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations.",
|
||||
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX300.jpg",
|
||||
"Metascore": "83",
|
||||
"imdbRating": "7.9",
|
||||
"imdbVotes": "876,575",
|
||||
"imdbID": "tt0499549",
|
||||
"Type": "movie",
|
||||
"Response": "True"
|
||||
}
|
||||
];
|
||||
|
||||
// Add your code below this line
|
||||
|
||||
var averageRating;
|
||||
|
||||
// Add your code above this line
|
||||
|
||||
console.log(averageRating);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: 587d7dab367417b2b2512b6f
|
||||
title: Use the some Method to Check that Any Elements in an Array Meet a Criteria
|
||||
localeTitle: Use el método para verificar que cualquier elemento de una matriz cumpla con los criterios
|
||||
challengeType: 1
|
||||
---
|
||||
|
||||
## Description
|
||||
<section id='description'>
|
||||
El <code>some</code> método funciona con matrices para comprobar si <em>cualquier</em> elemento pasa una prueba particular. Devuelve un valor booleano: <code>true</code> si alguno de los valores cumple los criterios, <code>false</code> si no.
|
||||
Por ejemplo, el siguiente código verificará si algún elemento de la matriz de <code>numbers</code> es menor que 10:
|
||||
<blockquote>var numbers = [10, 50, 8, 220, 110, 11];<br>numbers.some(function(currentValue) {<br> return currentValue < 10;<br>});<br>// Returns true</blockquote>
|
||||
</section>
|
||||
|
||||
## Instructions
|
||||
<section id='instructions'>
|
||||
Use <code>some</code> método dentro de la función <code>checkPositive</code> para verificar si algún elemento en <code>arr</code> es positivo. La función debe devolver un valor booleano.
|
||||
</section>
|
||||
|
||||
## Tests
|
||||
<section id='tests'>
|
||||
|
||||
```yml
|
||||
tests:
|
||||
- text: Su código debe utilizar <code>some</code> método.
|
||||
testString: 'assert(code.match(/\.some/g), "Your code should use the <code>some</code> method.");'
|
||||
- text: ' <code>checkPositive([1, 2, 3, -4, 5])</code> debe devolver <code>true</code> .'
|
||||
testString: 'assert(checkPositive([1, 2, 3, -4, 5]), "<code>checkPositive([1, 2, 3, -4, 5])</code> should return <code>true</code>.");'
|
||||
- text: ' <code>checkPositive([1, 2, 3, 4, 5])</code> debe devolver <code>true</code> .'
|
||||
testString: 'assert(checkPositive([1, 2, 3, 4, 5]), "<code>checkPositive([1, 2, 3, 4, 5])</code> should return <code>true</code>.");'
|
||||
- text: ' <code>checkPositive([-1, -2, -3, -4, -5])</code> debe devolver <code>false</code> .'
|
||||
testString: 'assert(!checkPositive([-1, -2, -3, -4, -5]), "<code>checkPositive([-1, -2, -3, -4, -5])</code> should return <code>false</code>.");'
|
||||
|
||||
```
|
||||
|
||||
</section>
|
||||
|
||||
## Challenge Seed
|
||||
<section id='challengeSeed'>
|
||||
|
||||
<div id='js-seed'>
|
||||
|
||||
```js
|
||||
function checkPositive(arr) {
|
||||
// Add your code below this line
|
||||
|
||||
|
||||
// Add your code above this line
|
||||
}
|
||||
checkPositive([1, 2, 3, -4, 5]);
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</section>
|
||||
|
||||
## Solution
|
||||
<section id='solution'>
|
||||
|
||||
```js
|
||||
// solution required
|
||||
```
|
||||
</section>
|
Reference in New Issue
Block a user