diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md index 507602f57d..2bd6c6b02f 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-a-module-script.md @@ -1,6 +1,6 @@ --- id: 5cddbfd622f1a59093ec611d -title: Create a Module Script +title: Crea un módulo para scripts challengeType: 6 forumTopicId: 301198 dashedName: create-a-module-script @@ -8,27 +8,27 @@ dashedName: create-a-module-script # --description-- -JavaScript started with a small role to play on an otherwise mostly HTML web. Today, it’s huge, and some websites are built almost entirely with JavaScript. In order to make JavaScript more modular, clean, and maintainable; ES6 introduced a way to easily share code among JavaScript files. This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them. In order to take advantage of this functionality, you need to create a script in your HTML document with a type of `module`. Here’s an example: +En sus inicios, JavaScript comenzó desempeñando un pequeño rol, cuando la web estaba mayormente hecha en HTML. Hoy Javascript se ha vuelto gigante y algunos sitios web están casi completamente construidos con JavaScript. Con la finalidad de hacer JavaScript más modular, limpio y mantenible, ES6 introdujo una manera de compartir código fácilmente entre archivos JavaScript. Esto implica exportar partes de un archivo para usar en uno o más archivos, e importar las partes que necesitas donde las necesites. Para aprovechar esta funcionalidad, necesitas crear un script en tu documento HTML con un `type` de `module`. A continuación, te presentamos un ejemplo: ```html ``` -A script that uses this `module` type can now use the `import` and `export` features you will learn about in the upcoming challenges. +Un script que utilice este `module` ahora podrá utilizar las caraterísticas `import` y `export`, sobre las que aprenderás en los próximos desafíos. # --instructions-- -Add a script to the HTML document of type `module` and give it the source file of `index.js` +Agrega un script de tipo `module` al documento HTML y asígnale el archivo fuente `index.js` # --hints-- -You should create a `script` tag. +Debes crear una etiqueta `script`. ```js assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g)); ``` -Your `script` tag should be of type `module`. +Tu etiqueta `input` debe tener un atributo `type` con un valor de `date`. ```js assert( @@ -38,7 +38,7 @@ assert( ); ``` -Your `script` tag should have a `src` of `index.js`. +Tu etiqueta `script` debe tener un `src` con el valor `index.js`. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md index ac32fc0848..b74c0d192c 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b58 -title: Create an Export Fallback with export default +title: Crear un fallback de exportación con export default challengeType: 1 forumTopicId: 301199 dashedName: create-an-export-fallback-with-export-default @@ -8,33 +8,33 @@ dashedName: create-an-export-fallback-with-export-default # --description-- -In the `export` lesson, you learned about the syntax referred to as a named export. This allowed you to make multiple functions and variables available for use in other files. +En la lección `export`, aprendiste sobre la sintaxis conocida como named export. Esto te permitió hacer disponibles múltiples funciones y variables para usar en otros archivos. -There is another `export` syntax you need to know, known as export default. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module. +Aquí hay otra sintaxis `export` que necesitas saber, conocida como export default. Usualmente utilizarás esta sintaxis, si es sólo un valor el que está siendo exportado desde un archivo. También es utilizado para crear valores fallback para un archivo o módulo. -Below are examples using `export default`: +A continuación hay ejemplos usando `export default`: ```js -// named function export default function add(x, y) { return x + y; } -// anonymous function export default function(x, y) { return x + y; } ``` -Since `export default` is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use `export default` with `var`, `let`, or `const` +La primera es una función nombrada, y la segunda es una función anónima. + +Ya que `export default` es usado para declarar un valor fallback para un módulo o archivo, sólo puedes tener un valor que sea exportación por defecto en cada módulo o archivo. Además, no puedes usar `export default` con `var`, `let`, o `const` # --instructions-- -The following function should be the fallback value for the module. Please add the necessary code to do so. +La siguiente función debe ser el valor fallback para el módulo. Por favor, añade el código necesario para hacerlo. # --hints-- -Your code should use `export` fallback. +Tu código debe utilizar un `export` fallback. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md index cd5c70bd6f..b13cd03bb1 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.md @@ -1,6 +1,6 @@ --- id: 587d7b8a367417b2b2512b4e -title: Create Strings using Template Literals +title: Crea strings usando plantillas literales challengeType: 1 forumTopicId: 301200 dashedName: create-strings-using-template-literals @@ -8,11 +8,11 @@ dashedName: create-strings-using-template-literals # --description-- -A new feature of ES6 is the template literal. This is a special type of string that makes creating complex strings easier. +Una nueva característica de ES6 es la plantilla literal. Este es un tipo especial de strings que facilita la creación de strings complejos. -Template literals allow you to create multi-line strings and to use string interpolation features to create strings. +Las plantillas literales te permiten crear strings multilínea y usar características de interpolación, para crear strings. -Consider the code below: +Fíjese en el código debajo: ```js const person = { @@ -20,23 +20,21 @@ const person = { age: 56 }; -// Template literal with multi-line and string interpolation const greeting = `Hello, my name is ${person.name}! I am ${person.age} years old.`; -console.log(greeting); // prints -// Hello, my name is Zodiac Hasbro! -// I am 56 years old. - +console.log(greeting); ``` -A lot of things happened there. Firstly, the example uses backticks (`` ` ``), not quotes (`'` or `"`), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting `\n` within strings. The `${variable}` syntax used above is a placeholder. Basically, you won't have to use concatenation with the `+` operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with `${` and `}`. Similarly, you can include other expressions in your string literal, for example `${a + b}`. This new way of creating strings gives you more flexibility to create robust strings. +La consola mostrará las cadenas `Hello, my name is Zodiac Hasbro!` y `I am 56 years old.`. + +Muchas cosas han ocurrido allí. En primer lugar, el ejemplo utiliza backticks (`` ` ``), no comillas (`'` o `"`), para envolver la cadena. En segundo lugar, observe que la cadena es multi-línea tanto en el código como cuando se imprime en pantalla. Esto guarda la inserción `\n` dentro de las cadenas. La sintaxis `${variable}` utilizada anteriormente es un marcador de posición. Básicamente, ya no tendrás que utilizar concatenación con el operador `+`. Para añadir variables a las cadenas, basta con colocar la variable en una plantilla de cadena y envolverla con `${` y `}`. Del mismo modo, puedes incluir otras expresiones en tu literal de cadena, por ejemplo `${a + b}`. Esta nueva forma de crear cadenas te da mayor flexibilidad para crear cadenas robustas. # --instructions-- -Use template literal syntax with backticks to create an array of list element (`li`) strings. Each list element's text should be one of the array elements from the `failure` property on the `result` object and have a `class` attribute with the value `text-warning`. The `makeList` function should return the array of list item strings. +Usa la sintaxis de plantilla literal con comillas invertidas para crear un arreglo de cadenas de elemento lista (`li`). El texto de cada elemento de lista debe ser uno de los elementos del arreglo de la propiedad `failure` en el objeto `result` y tener un atributo `class` con el valor `text-warning`. La función `makeList` debe devolver el arreglo de cadenas de elemento lista. -Use an iterator method (any kind of loop) to get the desired output (shown below). +Utiliza un método de iteración (cualquier tipo de bucle) para obtener el resultado deseado (mostrado a continuación). ```js [ @@ -48,7 +46,7 @@ Use an iterator method (any kind of loop) to get the desired output (shown below # --hints-- -`failuresList` should be an array containing `result failure` messages. +`failuresList` debe ser un arreglo que contenga los mensajes de `result failure`. ```js assert( @@ -56,7 +54,7 @@ assert( ); ``` -`failuresList` should be equal to the specified output. +`failuresList` debe ser igual que el resultado especificado. ```js assert( @@ -68,13 +66,13 @@ assert( ); ``` -Template strings and expression interpolation should be used. +Las cadenas de plantillas y la interpolación de expresiones deben ser usadas. ```js (getUserInput) => assert(getUserInput('index').match(/(`.*\${.*}.*`)/)); ``` -An iterator should be used. +Debe utilizarse un iterador. ```js (getUserInput) => diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md index a869196788..ef4c3a0b5e 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b41 -title: Declare a Read-Only Variable with the const Keyword +title: Declara una variable de sólo lectura con la palabra clave const challengeType: 1 forumTopicId: 301201 dashedName: declare-a-read-only-variable-with-the-const-keyword @@ -8,44 +8,46 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword # --description-- -The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword. +La palabra clave `let` no es la única manera nueva de declarar variables. En ES6, tú puedes declarar variables usando la palabra clave `const`. -`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned. +`const` tiene todas las características increíbles que tiene `let`, con el bono añadido de que las variables declaradas usando `const` son de solo lectura. Son un valor constante, lo que significa que una vez que una variable es asignada con `const`, no se puede reasignar. ```js const FAV_PET = "Cats"; -FAV_PET = "Dogs"; // returns error +FAV_PET = "Dogs"; ``` -As you can see, trying to reassign a variable declared with `const` will throw an error. You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore. +La consola mostrará un error debido a la reasignación del valor de `FAV_PET`. -**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array. +Como puedes ver, intentar reasignar una variable declarada con `const` arrojará un error. Siempre debes nombrar variables que no quieras reasignar usando la palabra clave `const`. Esto ayuda cuando intentas reasignar accidentalmente una variable que está destinada a permanecer constante. Una práctica común al nombrar constantes es utilizar todas las letras en mayúsculas, con palabras separadas por un guion bajo. + +**Nota:** Es común que los desarrolladores usen identificadores de variables en mayúsculas para valores inmutables y minúsculas o camelCase para valores mutables (objetos y arreglos). En un desafío posterior verás un ejemplo de un identificador de variable en minúsculas que se usa para un arreglo. # --instructions-- -Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps. +Cambia el código para que todas las variables sean declaradas usando `let` o `const`. Usa `let` cuando quieras que la variable cambie y `const` cuando quieras que la variable permanezca constante. Además, renombra las variables declaradas con `const` para adaptarse a las prácticas comunes, lo que significa que las constantes deben estar todas en mayúsculas. # --hints-- -`var` should not exist in your code. +`var` no debe existir en tu código. ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`SENTENCE` should be a constant variable declared with `const`. +`SENTENCE` debe ser una variable constante declarada con `const`. ```js (getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g)); ``` -`i` should be declared with `let`. +`i` debe ser declarada con `let`. ```js (getUserInput) => assert(getUserInput('index').match(/(let i)/g)); ``` -`console.log` should be changed to print the `SENTENCE` variable. +`console.log` debe cambiarse para imprimir la variable `SENTENCE`. ```js (getUserInput) => diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md index 7792ee384b..28187048b3 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b3f -title: Explore Differences Between the var and let Keywords +title: Explora las diferencias entre las palabras claves var y let challengeType: 1 forumTopicId: 301202 dashedName: explore-differences-between-the-var-and-let-keywords @@ -8,49 +8,52 @@ dashedName: explore-differences-between-the-var-and-let-keywords # --description-- -One of the biggest problems with declaring variables with the `var` keyword is that you can overwrite variable declarations without an error. +Uno de los grandes problemas con la declaración de variables, usando la palabra clave `var`, es que tu puedes sobrescribir declaraciones de variables sin un error. ```js var camper = 'James'; var camper = 'David'; console.log(camper); -// logs 'David' ``` -As you can see in the code above, the `camper` variable is originally declared as `James` and then overridden to be `David`. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult. -A new keyword called `let` was introduced in ES6 to solve this potential issue with the `var` keyword. If you were to replace `var` with `let` in the variable declarations of the code above, the result would be an error. +Aquí la consola mostrará la cadena de caracteres `David`. + +Como puedes ver en el código anterior, la variable `camper` es originalmente declarada como `James` luego de anularse pasa a ser `David`. En una aplicación pequeña, puede que no te topes con este tipo de problema, pero cuando tu código se vuelve mas grande, puede que accidentalmente sobrescribas una variable que no pretendías sobrescribir. Debido a que este comportamiento no arroja un error, buscar y corregir errores se vuelve mas difícil. +Una nueva palabra clave llamada `let` que fue introducida en ES6 para resolver este posible problema con la palabra clave `var`. Si reemplazas `var` por `let` en las declaraciones de variables del código anterior, el resultado será un error. ```js let camper = 'James'; -let camper = 'David'; // throws an error +let camper = 'David'; ``` -This error can be seen in the console of your browser. So unlike `var`, when using `let`, a variable with the same name can only be declared once. Note the `"use strict"`. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance: +Este error se puede ver en la consola de tu navegador. Así que a diferencia de `var`, al usar `let`, una variable con el mismo nombre solo puede declararse una vez. Toma en cuenta el `"use strict"` (uso estricto). Esto habilita el modo estricto, el cual captura errores comunes de programación y acciones "inseguras". Por ejemplo: ```js "use strict"; -x = 3.14; // throws an error because x is not declared +x = 3.14; ``` +Esto mostrará el error `x is not defined`. + # --instructions-- -Update the code so it only uses the `let` keyword. +Actualiza el código para que solo utilice la palabra clave `let`. # --hints-- -`var` should not exist in the code. +`var` no debe existir en el código. ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`catName` should be `Oliver`. +`catName` debe ser la cadena `Oliver`. ```js assert(catName === 'Oliver'); ``` -`quote` should be `"Oliver says Meow!"` +`quote` debe ser la cadena `Oliver says Meow!` ```js assert(quote === 'Oliver says Meow!'); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md index 90799c6bba..e65e7b47a6 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b42 -title: Mutate an Array Declared with const +title: Muta un arreglo declarado con const challengeType: 1 forumTopicId: 301206 dashedName: mutate-an-array-declared-with-const @@ -8,40 +8,42 @@ dashedName: mutate-an-array-declared-with-const # --description-- -The `const` declaration has many use cases in modern JavaScript. +La declaración `const` tiene muchos casos de uso, en el actual JavaScript. -Some developers prefer to assign all their variables using `const` by default, unless they know they will need to reassign the value. Only in that case, they use `let`. +Algunos desarrolladores, prefieren asignar todas sus variables utilizando `const` por defecto, salvo que sepan que necesitarán reasignar el valor. Sólo en ese caso, utilizan `let`. -However, it is important to understand that objects (including arrays and functions) assigned to a variable using `const` are still mutable. Using the `const` declaration only prevents reassignment of the variable identifier. +Sin embargo, es importante comprender que los objetos (incluyendo arreglos y funciones), asignados a una variable usando `const` siguen siendo mutables. Usar la declaración `const` sólo previene la reasignación del identificador de una variable. ```js const s = [5, 6, 7]; -s = [1, 2, 3]; // throws error, trying to assign a const -s[2] = 45; // works just as it would with an array declared with var or let -console.log(s); // returns [5, 6, 45] +s = [1, 2, 3]; +s[2] = 45; +console.log(s); ``` -As you can see, you can mutate the object `[5, 6, 7]` itself and the variable `s` will still point to the altered array `[5, 6, 45]`. Like all arrays, the array elements in `s` are mutable, but because `const` was used, you cannot use the variable identifier `s` to point to a different array using the assignment operator. +`s = [1, 2, 3]` resultará en un error. El `console.log` mostrará el valor `[5, 6, 45]`. + +Como puedes ver, puedes mutar el objeto `[5, 6, 7]` en sí mismo y la variable `s` seguirá apuntado al arreglo alterado `[5, 6, 45]`. Como en todos los arreglos, los elementos del arreglo en `s` son mutables, pero debido a que se utilizó `const`, no puedes utilizar el identificador de la variable `s` para apuntar a un arreglo diferente usando el operador de asignación. # --instructions-- -An array is declared as `const s = [5, 7, 2]`. Change the array to `[2, 5, 7]` using various element assignments. +Un arreglo es declarado como `const s = [5, 7, 2]`. Cambia el arreglo a `[2, 5, 7]` utilizando varias asignaciones de elementos. # --hints-- -You should not replace `const` keyword. +No debes reemplazar la palabra clave `const`. ```js (getUserInput) => assert(getUserInput('index').match(/const/g)); ``` -`s` should be a constant variable (by using `const`). +`s` debe ser una variable constante (utilizando `const`). ```js (getUserInput) => assert(getUserInput('index').match(/const\s+s/g)); ``` -You should not change the original array declaration. +No debes cambiar la declaración original del arreglo. ```js (getUserInput) => @@ -52,7 +54,7 @@ You should not change the original array declaration. ); ``` -`s` should be equal to `[2, 5, 7]`. +`s` debe ser igual a `[2, 5, 7]`. ```js assert.deepEqual(s, [2, 5, 7]); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md index fb97d40308..c51987f7f0 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.md @@ -1,6 +1,6 @@ --- id: 598f48a36c8c40764b4e52b3 -title: Prevent Object Mutation +title: Prevenir la mutación del objeto challengeType: 1 forumTopicId: 301207 dashedName: prevent-object-mutation @@ -8,9 +8,9 @@ dashedName: prevent-object-mutation # --description-- -As seen in the previous challenge, `const` declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function `Object.freeze` to prevent data mutation. +Como se vio en el desafío anterior, la declaración `const` por sí sola no protege la información de la mutación. Para asegurar que tu información no cambie, JavaScript provee una función `Object.freeze` para prevenir la mutación de datos. -Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error. +Una vez que el objeto está congelado, ya no puedes agregar, actualizar o borrar propiedades alojadas en él. Cualquier intento de cambiar el objeto será rechazado sin ningún error. ```js let obj = { @@ -18,32 +18,33 @@ let obj = { review:"Awesome" }; Object.freeze(obj); -obj.review = "bad"; // will be ignored. Mutation not allowed -obj.newProp = "Test"; // will be ignored. Mutation not allowed +obj.review = "bad"; +obj.newProp = "Test"; console.log(obj); -// { name: "FreeCodeCamp", review:"Awesome"} ``` +Las asignaciones `obj.review` y `obj.newProp` provocarán errores y la consola mostrará el valor `{ name: "FreeCodeCamp", review: "Awesome" }`. + # --instructions-- -In this challenge you are going to use `Object.freeze` to prevent mathematical constants from changing. You need to freeze the `MATH_CONSTANTS` object so that no one is able to alter the value of `PI`, add, or delete properties. +En este desafío vas a utilizar `Object.freeze` para prevenir el cambio de constantes matemáticas. Necesitas congelar el objeto `MATH_CONSTANTS` para que nadie pueda alterar el valor de `PI`, añadir o borrar propiedades. # --hints-- -You should not replace `const` keyword. +No debes reemplazar la palabra clave `const`. ```js (getUserInput) => assert(getUserInput('index').match(/const/g)); ``` -`MATH_CONSTANTS` should be a constant variable (by using `const`). +`MATH_CONSTANTS` debe ser una variable constante (utilizando `const`). ```js (getUserInput) => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g)); ``` -You should not change original `MATH_CONSTANTS`. +No debes modificar la declaración original de `MATH_CONSTANTS`. ```js (getUserInput) => @@ -54,7 +55,7 @@ You should not change original `MATH_CONSTANTS`. ); ``` -`PI` should equal `3.14`. +`PI` debe ser igual a `3.14`. ```js assert(PI === 3.14); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md index b804b67af1..ec374b4f91 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.md @@ -1,6 +1,6 @@ --- id: 587d7b88367417b2b2512b46 -title: Set Default Parameters for Your Functions +title: Establece parámetros por defecto para tus funciones challengeType: 1 forumTopicId: 301209 dashedName: set-default-parameters-for-your-functions @@ -8,38 +8,40 @@ dashedName: set-default-parameters-for-your-functions # --description-- -In order to help us create more flexible functions, ES6 introduces default parameters for functions. +Para ayudarnos a crear funciones más flexibles, ES6 introduce parametros por defecto para funciones. -Check out this code: +Echa un vistazo, al siguente código: ```js const greeting = (name = "Anonymous") => "Hello " + name; -console.log(greeting("John")); // Hello John -console.log(greeting()); // Hello Anonymous +console.log(greeting("John")); +console.log(greeting()); ``` -The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter `name` will receive its default value `"Anonymous"` when you do not provide a value for the parameter. You can add default values for as many parameters as you want. +La consola mostrará las cadenas `Hello John` y `Hello Anonymous`. + +El parámetro por defecto entra en juego cuando el argumento no es especificado (es indefinido). Como puedes ver en el ejemplo anterior, el parámetro `name` recibirá su valor por defecto `Anonymous` cuando no proveas un valor para el parámetro. Puede agregar valores por defecto para tantos parámetros como desees. # --instructions-- -Modify the function `increment` by adding default parameters so that it will add 1 to `number` if `value` is not specified. +Modifica la función `increment` agregando parámetros por defecto para que sume 1 a `number` si `value` no se especifica. # --hints-- -The result of `increment(5, 2)` should be `7`. +El resultado de `increment(5, 2)` debe ser `7`. ```js assert(increment(5, 2) === 7); ``` -The result of `increment(5)` should be `6`. +El resultado de `increment(5)` debe ser `6`. ```js assert(increment(5) === 6); ``` -A default parameter value of `1` should be used for `value`. +Un valor de parámetro por defecto de `1` debe utilizarse para `value`. ```js assert(code.match(/value\s*=\s*1/g)); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md index b1e92a91d2..29da4da859 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.md @@ -1,6 +1,6 @@ --- id: 587d7b87367417b2b2512b43 -title: Use Arrow Functions to Write Concise Anonymous Functions +title: Usa funciones flecha para escribir funciones anónimas de manera breve challengeType: 1 forumTopicId: 301211 dashedName: use-arrow-functions-to-write-concise-anonymous-functions @@ -8,9 +8,9 @@ dashedName: use-arrow-functions-to-write-concise-anonymous-functions # --description-- -In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else. +En JavaScript, usualmente no necesitas nombrar tus funciones, especialmente cuando se pasa una función como argumento a otra función. En su lugar, creamos funciones inline (en línea). No necesitamos nombrar estas funciones porque no las reutilizamos en otro lugar. -To achieve this, we often use the following syntax: +Para lograr esto, por lo general se usa la siguiente sintaxis: ```js const myFunc = function() { @@ -19,7 +19,7 @@ const myFunc = function() { } ``` -ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use **arrow function syntax**: +ES6 nos proporciona el azúcar sintáctico, para no tener que escribir funciones anónimas de este modo. En su lugar, puedes usar la **sintaxis de función flecha**: ```js const myFunc = () => { @@ -28,45 +28,45 @@ const myFunc = () => { } ``` -When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword `return` as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements: +Cuando la función no posee cuerpo y sólo tiene un valor de retorno, la sintaxis de "función de flecha", te permite omitir la palabra clave `return`, así como los corchetes que rodean el código. Esto ayuda a simplificar las funciones más pequeñas en sentencias de una sola línea: ```js const myFunc = () => "value"; ``` -This code will still return the string `value` by default. +Este código todavía retorna el string `value` por defecto. # --instructions-- -Rewrite the function assigned to the variable `magic` which returns a `new Date()` to use arrow function syntax. Also, make sure nothing is defined using the keyword `var`. +Reescribe la función asignada a la variable `magic`, la cual devuelve una `new Date()`, utilizando la sintaxis de función flecha. Además, asegúrate de que nada esté definido usando la palabra clave `var`. # --hints-- -User should replace `var` keyword. +Debes reemplazar la palabra clave `var`. ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`magic` should be a constant variable (by using `const`). +`magic` debe ser una variable constante (utilizando `const`). ```js (getUserInput) => assert(getUserInput('index').match(/const\s+magic/g)); ``` -`magic` should be a `function`. +`magic` debe ser una función (`function`). ```js assert(typeof magic === 'function'); ``` -`magic()` should return correct date. +`magic()` debe devolver la fecha correcta. ```js assert(magic().setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0)); ``` -`function` keyword should not be used. +La palabra clave `function` no debe ser usada. ```js (getUserInput) => assert(!getUserInput('index').match(/function/g)); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md index 9e27796ab3..cb33f49a4e 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.md @@ -1,6 +1,6 @@ --- id: 587d7b8b367417b2b2512b53 -title: Use class Syntax to Define a Constructor Function +title: Usa sintaxis de clases para definir una función constructora challengeType: 1 forumTopicId: 301212 dashedName: use-class-syntax-to-define-a-constructor-function @@ -8,11 +8,11 @@ dashedName: use-class-syntax-to-define-a-constructor-function # --description-- -ES6 provides a new syntax to create objects, using the class keyword. +ES6 proporciona una nueva sintaxis para crear objetos, usando la palabra clave class. -It should be noted that the `class` syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc. +Debemos notar que la sintaxis `class` es sólo sintaxis, y no una implementación completa basada en clases de un paradigma orientado a objetos, a diferencia de lenguajes como Java, Python, Ruby, etc. -In ES5, we usually define a constructor function and use the `new` keyword to instantiate an object. +En ES5, normalmente definimos una función `constructor` y usamos la palabra clave `new` para instanciar un objeto. ```js var SpaceShuttle = function(targetPlanet){ @@ -21,7 +21,7 @@ var SpaceShuttle = function(targetPlanet){ var zeus = new SpaceShuttle('Jupiter'); ``` -The `class` syntax simply replaces the constructor function creation: +La sintaxis `class` simplemente reemplaza la creación de la función `constructor`: ```js class SpaceShuttle { @@ -32,21 +32,21 @@ class SpaceShuttle { const zeus = new SpaceShuttle('Jupiter'); ``` -It should be noted that the `class` keyword declares a new function, to which a constructor is added. This constructor is invoked when `new` is called to create a new object. -**Notes:** +Debe tenerse en cuenta que la palabra clave `class` declara una nueva función, a la cual se añade un constructor. Este constructor se invoca cuando `new` es llamado para crear un nuevo objeto. -- UpperCamelCase should be used by convention for ES6 class names, as in `SpaceShuttle` used above. -- The constructor method is a special method for creating and initializing an object created with a class. You will learn more about it in the Object Oriented Programming section of the JavaScript Algorithms And Data Structures Certification. +**Nota:** UpperCamelCase debe ser utilizado por convención para nombres de clase en ES6, como `SpaceShuttle` fue usado arriba. + +El método `constructor` es un método especial para crear e inicializar un objeto creado con una clase. Aprenderás más sobre ello en la sección de Programación Orientada a Objetos de la Certificación en Algoritmos de JavaScript y Estructuras de Datos. # --instructions-- -Use the `class` keyword and write a constructor to create the `Vegetable` class. +Usa la palabra clave `class` y escribe un `constructor` para crear la clase `Vegetable`. -The `Vegetable` class allows you to create a vegetable object with a property `name` that gets passed to the constructor. +La clase `Vegetable` te permite crear un objeto vegetal con una propiedad `name` que es pasada al `constructor`. # --hints-- -`Vegetable` should be a `class` with a defined `constructor` method. +`Vegetable` debe ser una clase (`class`) con un método `constructor` definido. ```js assert( @@ -54,13 +54,13 @@ assert( ); ``` -`class` keyword should be used. +La palabra clave `class` debe ser utilizada. ```js assert(code.match(/class/g)); ``` -`Vegetable` should be able to be instantiated. +`Vegetable` debe ser capaz de ser instanciada. ```js assert(() => { @@ -69,7 +69,7 @@ assert(() => { }); ``` -`carrot.name` should return `carrot`. +`carrot.name` debe devolver `carrot`. ```js assert(carrot.name == 'carrot'); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md index 04e7ec825a..02a50278f6 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.md @@ -1,6 +1,6 @@ --- id: 587d7b8c367417b2b2512b54 -title: Use getters and setters to Control Access to an Object +title: Utiliza getters (accesores) y setters (mutadores) para controlar el acceso a un objeto challengeType: 1 forumTopicId: 301220 dashedName: use-getters-and-setters-to-control-access-to-an-object @@ -8,13 +8,13 @@ dashedName: use-getters-and-setters-to-control-access-to-an-object # --description-- -You can obtain values from an object and set the value of a property within an object. +Puedes obtener valores de un objeto y establecer el valor de una propiedad dentro de un objeto. -These are classically called getters and setters. +Estas operaciones clásicamente se llaman getters y setters. -Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable. +Las funciones getter están destinadas a simplemente devolver (get) el valor de la variable privada de un objeto al usuario sin que el usuario acceda directamente a la variable privada. -Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely. +Las funciones setter están destinadas a modificar (set) el valor de la variable privada de un objeto basado en el valor pasado a la función setter. Este cambio podría implicar cálculos, o incluso sobrescribir completamente el valor anterior. ```js class Book { @@ -31,30 +31,34 @@ class Book { } } const novel = new Book('anonymous'); -console.log(novel.writer); // anonymous +console.log(novel.writer); novel.writer = 'newAuthor'; -console.log(novel.writer); // newAuthor +console.log(novel.writer); ``` -Notice the syntax used to invoke the getter and setter. They do not even look like functions. Getters and setters are important because they hide internal implementation details. **Note:** It is convention to precede the name of a private variable with an underscore (`_`). However, the practice itself does not make a variable private. +La consola mostrará las cadenas `anonymous` y `newAuthor`. + +Ten en cuenta la sintaxis usada para invocar el getter y el setter. Ni siquiera se ven como funciones. Los getter y los setter son importantes porque ocultan los detalles internos de la implementación. + +**Nota:** Es convención preceder el nombre de una variable privada con un guión bajo (`_`). Sin embargo, la práctica en sí misma no hace una variable privada. # --instructions-- -Use the `class` keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature. +Utiliza la palabra clave `class` para crear una clase `Thermostat`. El `constructor` acepta una temperatura Fahrenheit. -In the class, create a `getter` to obtain the temperature in Celsius and a `setter` to set the temperature in Celsius. +En la clase, crea un `getter` para obtener la temperatura en Celsius y un `setter` para ajustar la temperatura en Celsius. -Remember that `C = 5/9 * (F - 32)` and `F = C * 9.0 / 5 + 32`, where `F` is the value of temperature in Fahrenheit, and `C` is the value of the same temperature in Celsius. +Recuerda que `C = 5/9 * (F - 32)` y `F = C * 9.0 / 5 + 32` donde `F` es el valor de la temperatura en Fahrenheit y `C` es el valor de la misma temperatura en Celsius. -**Note:** When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius. +**Nota:** Cuando implementes esto, rastrearás la temperatura dentro de la clase en una escala, ya sea Fahrenheit o Celsius. -This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track. +Este es el poder de un getter y un setter. Estás creando una API para otro usuario, que puede obtener el resultado correcto independientemente de cuál estés rastreando. -In other words, you are abstracting implementation details from the user. +En otras palabras, estás abstrayendo los detalles de la implementación del usuario. # --hints-- -`Thermostat` should be a `class` with a defined `constructor` method. +`Thermostat` debe ser una `class` con un método `constructor` definido. ```js assert( @@ -63,13 +67,13 @@ assert( ); ``` -`class` keyword should be used. +La palabra clave `class` debe ser utilizada. ```js assert(code.match(/class/g)); ``` -`Thermostat` should be able to be instantiated. +`Thermostat` debe ser capaz de ser instanciado. ```js assert( @@ -80,7 +84,7 @@ assert( ); ``` -When instantiated with a Fahrenheit value, `Thermostat` should set the correct temperature. +Cuando se crea una instancia con un valor de Fahrenheit, `Thermostat` debe establecer la temperatura (`temperature`) correcta. ```js assert( @@ -91,7 +95,7 @@ assert( ); ``` -A `getter` should be defined. +Un `getter` debe ser definido. ```js assert( @@ -105,7 +109,7 @@ assert( ); ``` -A `setter` should be defined. +Un `setter` debe ser definido. ```js assert( @@ -119,7 +123,7 @@ assert( ); ``` -Calling the `setter` with a Celsius value should set the temperature. +Llamar al `setter` con un valor Celsius debe establecer `temperature`. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md index 390cb0933c..09578baf5f 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.md @@ -1,6 +1,6 @@ --- id: 587d7b88367417b2b2512b44 -title: Write Arrow Functions with Parameters +title: Escribe funciones flecha con parámetros challengeType: 1 forumTopicId: 301223 dashedName: write-arrow-functions-with-parameters @@ -8,48 +8,49 @@ dashedName: write-arrow-functions-with-parameters # --description-- -Just like a regular function, you can pass arguments into an arrow function. +Al igual que una función regular, puedes pasar argumentos a una función flecha. ```js -// doubles input value and returns it const doubler = (item) => item * 2; -doubler(4); // returns 8 +doubler(4); ``` -If an arrow function has a single parameter, the parentheses enclosing the parameter may be omitted. +`doubler(4)` devolvería el valor `8`. + +Si una función flecha tiene un solo parámetro, los paréntesis que encierran el parámetro pueden ser omitidos. ```js -// the same function, without the parameter parentheses const doubler = item => item * 2; ``` -It is possible to pass more than one argument into an arrow function. +Es posible pasar más de un argumento a una función flecha. ```js -// multiplies the first input value by the second and returns it const multiplier = (item, multi) => item * multi; -multiplier(4, 2); // returns 8 +multiplier(4, 2); ``` +`multiplier(4, 2)` devolverá el valor `8`. + # --instructions-- -Rewrite the `myConcat` function which appends contents of `arr2` to `arr1` so that the function uses arrow function syntax. +Reescribe la función `myConcat` que añade el contenido de `arr2` a `arr1` para que la función use la sintaxis de función flecha. # --hints-- -You should replace the `var` keyword. +Debes reemplazar la palabra clave `var`. ```js (getUserInput) => assert(!getUserInput('index').match(/var/g)); ``` -`myConcat` should be a constant variable (by using `const`). +`myConcat` debe ser una variable constante (utilizando `const`). ```js (getUserInput) => assert(getUserInput('index').match(/const\s+myConcat/g)); ``` -`myConcat` should be an arrow function with two parameters +`myConcat` debe ser una función de flecha con dos parámetros ```js assert( @@ -58,13 +59,13 @@ assert( ); ``` -`myConcat()` should return `[1, 2, 3, 4, 5]`. +`myConcat()` debe devolver `[1, 2, 3, 4, 5]`. ```js assert.deepEqual(myConcat([1, 2], [3, 4, 5]), [1, 2, 3, 4, 5]); ``` -`function` keyword should not be used. +La palabra clave `function` no debe ser usada. ```js (getUserInput) => assert(!getUserInput('index').match(/function/g)); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md index b7bd2904d8..cef2c55c1f 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.md @@ -1,6 +1,6 @@ --- id: 587d7b8b367417b2b2512b50 -title: Write Concise Declarative Functions with ES6 +title: Escribe funciones declarativas concisas con ES6 challengeType: 1 forumTopicId: 301224 dashedName: write-concise-declarative-functions-with-es6 @@ -8,7 +8,7 @@ dashedName: write-concise-declarative-functions-with-es6 # --description-- -When defining functions within objects in ES5, we have to use the keyword `function` as follows: +Al definir funciones dentro de objetos en ES5, tenemos que utilizar la palabra clave `function` de la siguiente manera: ```js const person = { @@ -19,7 +19,7 @@ const person = { }; ``` -With ES6, You can remove the `function` keyword and colon altogether when defining functions in objects. Here's an example of this syntax: +Con ES6, puedes eliminar la palabra clave `function` y los dos puntos al definir funciones en objetos. Aquí hay un ejemplo de esta sintaxis: ```js const person = { @@ -32,17 +32,17 @@ const person = { # --instructions-- -Refactor the function `setGear` inside the object `bicycle` to use the shorthand syntax described above. +Refactoriza la función `setGear` dentro del objeto `bicycle` para que utilice la sintaxis abreviada descrita arriba. # --hints-- -Traditional function expression should not be used. +La expresión tradicional "function" no debe ser utilizada. ```js (getUserInput) => assert(!__helpers.removeJSComments(code).match(/function/)); ``` -`setGear` should be a declarative function. +`setGear` debe ser una función declarativa. ```js assert( @@ -50,7 +50,7 @@ assert( ); ``` -`bicycle.setGear(48)` should change the `gear` value to 48. +`bicycle.setGear(48)` debe cambiar el valor de `gear` a 48. ```js assert(new bicycle.setGear(48).gear === 48); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md index 33dabc5d3a..417076079a 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-object-property-shorthand.md @@ -1,6 +1,6 @@ --- id: 587d7b8a367417b2b2512b4f -title: Write Concise Object Literal Declarations Using Object Property Shorthand +title: Escribe declaraciones concisas de objecto literales usando la abreviatura de propiedad de objeto challengeType: 1 forumTopicId: 301225 dashedName: write-concise-object-literal-declarations-using-object-property-shorthand @@ -8,9 +8,9 @@ dashedName: write-concise-object-literal-declarations-using-object-property-shor # --description-- -ES6 adds some nice support for easily defining object literals. +ES6 añade un buen soporte para definir fácilmente objetos literales. -Consider the following code: +Considera el siguiente código: ```js const getMousePosition = (x, y) => ({ @@ -19,7 +19,7 @@ const getMousePosition = (x, y) => ({ }); ``` -`getMousePosition` is a simple function that returns an object containing two properties. ES6 provides the syntactic sugar to eliminate the redundancy of having to write `x: x`. You can simply write `x` once, and it will be converted to`x: x` (or something equivalent) under the hood. Here is the same function from above rewritten to use this new syntax: +`getMousePosition` es una función simple que devuelve un objeto que contiene dos propiedades. ES6 proporciona el azúcar sintáctico para eliminar la redundancia de tener que escribir `x: x`. Puedes simplemente escribir `x` una vez, y se convertirá en `x: x` (o algo equivalente) de la nada. Aquí está la misma función de arriba reescrita para usar esta nueva sintaxis: ```js const getMousePosition = (x, y) => ({ x, y }); @@ -27,11 +27,11 @@ const getMousePosition = (x, y) => ({ x, y }); # --instructions-- -Use object property shorthand with object literals to create and return an object with `name`, `age` and `gender` properties. +Utiliza la abreviatura de propiedad de objeto con objetos literales para crear y devolver un objeto con las propiedades `name`, `age` y `gender`. # --hints-- -`createPerson("Zodiac Hasbro", 56, "male")` should return `{name: "Zodiac Hasbro", age: 56, gender: "male"}`. +`createPerson("Zodiac Hasbro", 56, "male")` debe devolver `{name: "Zodiac Hasbro", age: 56, gender: "male"}`. ```js assert.deepEqual( @@ -40,7 +40,7 @@ assert.deepEqual( ); ``` -Your code should not use `key:value`. +Tu código no debe usar `key:value`. ```js (getUserInput) => assert(!getUserInput('index').match(/:/g)); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.md index 9f702386e0..3b0a35f278 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.md @@ -1,6 +1,6 @@ --- id: 587d7daa367417b2b2512b6b -title: Split a String into an Array Using the split Method +title: Divide una cadena en un arreglo utilizando el método "split" challengeType: 1 forumTopicId: 18305 dashedName: split-a-string-into-an-array-using-the-split-method @@ -8,35 +8,35 @@ dashedName: split-a-string-into-an-array-using-the-split-method # --description-- -The `split` method splits a string into an array of strings. It takes an argument for the delimiter, which can be a character to use to break up the string or a regular expression. For example, if the delimiter is a space, you get an array of words, and if the delimiter is an empty string, you get an array of each character in the string. +El método `split` divide una cadena en un arreglo de cadenas. Se necesita un argumento para el delimitador, el cual puede ser un carácter para separar la cadena o una expresión regular. Por ejemplo, si el delimitador es un espacio, se obtiene un arreglo de palabras y si el delimitador es una cadena vacía, se obtiene un arreglo de cada carácter en la cadena. -Here are two examples that split one string by spaces, then another by digits using a regular expression: +Aquí hay dos ejemplos que dividen una cadena por espacios, luego otra por dígitos utilizando una expresión regular: ```js var str = "Hello World"; var bySpace = str.split(" "); -// Sets bySpace to ["Hello", "World"] var otherString = "How9are7you2today"; var byDigits = otherString.split(/\d/); -// Sets byDigits to ["How", "are", "you", "today"] ``` -Since strings are immutable, the `split` method makes it easier to work with them. +`bySpace` tendrá el valor `["Hello", "World"]` y `byDigits` tendrá el valor `["How", "are", "you", "today"]`. + +Dado que las cadenas son inmutables, el método `split` facilita el trabajo con ellas. # --instructions-- -Use the `split` method inside the `splitify` function to split `str` into an array of words. The function should return the array. Note that the words are not always separated by spaces, and the array should not contain punctuation. +Utiliza el método `split` dentro de la función `splitify` para dividir `str` en un arreglo de palabras. La función debe devolver un arreglo. Ten en cuenta que las palabras no siempre están separadas por espacios y que el arreglo no debe contener signos de puntuación. # --hints-- -Your code should use the `split` method. +Tu código debe usar el método `split`. ```js assert(code.match(/\.split/g)); ``` -`splitify("Hello World,I-am code")` should return `["Hello", "World", "I", "am", "code"]`. +`splitify("Hello World,I-am code")` debe devolver `["Hello", "World", "I", "am", "code"]`. ```js assert( @@ -45,7 +45,7 @@ assert( ); ``` -`splitify("Earth-is-our home")` should return `["Earth", "is", "our", "home"]`. +`splitify("Earth-is-our home")` debe devolver `["Earth", "is", "our", "home"]`. ```js assert( @@ -54,7 +54,7 @@ assert( ); ``` -`splitify("This.is.a-sentence")` should return `["This", "is", "a", "sentence"]`. +`splitify("This.is.a-sentence")` debe devolver `["This", "is", "a", "sentence"]`. ```js assert( diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.md index ee3572d6ae..08b1cc83fe 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.md @@ -1,6 +1,6 @@ --- id: 587d7b8e367417b2b2512b5c -title: Understand Functional Programming Terminology +title: Comprende la terminología de la programación funcional challengeType: 1 forumTopicId: 301240 dashedName: understand-functional-programming-terminology @@ -8,47 +8,47 @@ dashedName: understand-functional-programming-terminology # --description-- -The FCC Team had a mood swing and now wants two types of tea: green tea and black tea. General Fact: Client mood swings are pretty common. +El equipo de FCC tuvo un cambio de humor y ahora quiere dos tipos de té: té verde y té negro. Hecho general: Los cambios del estado de ánimo de los clientes son bastante concurrentes. -With that information, we'll need to revisit the `getTea` function from last challenge to handle various tea requests. We can modify `getTea` to accept a function as a parameter to be able to change the type of tea it prepares. This makes `getTea` more flexible, and gives the programmer more control when client requests change. +Con esa información, tendremos que volver a visitar la función `getTea` del último desafío para manejar varias solicitudes de té. Podemos modificar `getTea` para aceptar una función como parámetro y así poder cambiar el tipo de té que prepara. Esto hace que `getTea` sea más flexible y le da al programador más control cuando las solicitudes del cliente cambian. -But first, let's cover some functional terminology: +Pero primero, cubramos alguna terminología de la programación funcional: -Callbacks are the functions that are slipped or passed into another function to decide the invocation of that function. You may have seen them passed to other methods, for example in `filter`, the callback function tells JavaScript the criteria for how to filter an array. +Callbacks son las funciones que se deslizan o pasan a otra función para decidir la invocación de esa función. Es posible que las hayas visto pasar a otros métodos, por ejemplo en `filter`, la función callback le dice a JavaScript los criterios para filtrar un arreglo. -Functions that can be assigned to a variable, passed into another function, or returned from another function just like any other normal value, are called first class functions. In JavaScript, all functions are first class functions. +Las funciones que pueden ser asignadas a una variable, pasadas a otra función o devueltas desde otra función como cualquier otro valor normal, se llaman funciones de primera clase. En JavaScript, todas las funciones son funciones de primera clase. -The functions that take a function as an argument, or return a function as a return value are called higher order functions. +Las funciones que toman una función como argumento o devuelven una función como valor de retorno se llaman funciones de orden superior. -When the functions are passed in to another function or returned from another function, then those functions which gets passed in or returned can be called a lambda. +Cuando las funciones son pasadas a otra función o devueltas desde otra función, entonces esas funciones que se pasan o devuelven pueden llamarse una lambda. # --instructions-- -Prepare 27 cups of green tea and 13 cups of black tea and store them in `tea4GreenTeamFCC` and `tea4BlackTeamFCC` variables, respectively. Note that the `getTea` function has been modified so it now takes a function as the first argument. +Prepara 27 tazas de té verde (green tea) y 13 tazas de té negro (black tea) y almacénalas en las variables `tea4GreenTeamFCC` y `tea4BlackTeamFCC`, respectivamente. Ten en cuenta que la función `getTea` ha sido modificada por lo que ahora recibe una función como primer argumento. -Note: The data (the number of cups of tea) is supplied as the last argument. We'll discuss this more in later lessons. +Nota: Los datos (el número de tazas de té) son suministrados como el último argumento. Discutiremos más sobre esto en lecciones posteriores. # --hints-- -The `tea4GreenTeamFCC` variable should hold 27 cups of green tea for the team. +La variable `tea4GreenTeamFCC` debe contener 27 tazas de té verde para el equipo. ```js assert(tea4GreenTeamFCC.length === 27); ``` -The `tea4GreenTeamFCC` variable should hold cups of green tea. +La variable `tea4GreenTeamFCC` debe contener tazas de té verde. ```js assert(tea4GreenTeamFCC[0] === 'greenTea'); ``` -The `tea4BlackTeamFCC` variable should hold 13 cups of black tea. +La variable `tea4BlackTeamFCC` debe contener 13 tazas de té negro. ```js assert(tea4BlackTeamFCC.length === 13); ``` -The `tea4BlackTeamFCC` variable should hold cups of black tea. +La variable `tea4BlackTeamFCC` debe contener tazas de té negro. ```js assert(tea4BlackTeamFCC[0] === 'blackTea'); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.md index f717be6c1e..218998d858 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.md @@ -1,6 +1,6 @@ --- id: 587d7b8e367417b2b2512b5d -title: Understand the Hazards of Using Imperative Code +title: Comprende los peligros de usar el código imperativo challengeType: 1 forumTopicId: 301241 dashedName: understand-the-hazards-of-using-imperative-code @@ -8,31 +8,31 @@ dashedName: understand-the-hazards-of-using-imperative-code # --description-- -Functional programming is a good habit. It keeps your code easy to manage, and saves you from sneaky bugs. But before we get there, let's look at an imperative approach to programming to highlight where you may have issues. +La programación funcional es un buen hábito. Mantiene tu código fácil de manejar y evita que tengas errores incómodos. Pero antes de llegar allí, veamos un enfoque imperativo de la programación para destacar dónde pueden tener problemas. -In English (and many other languages), the imperative tense is used to give commands. Similarly, an imperative style in programming is one that gives the computer a set of statements to perform a task. +En inglés (y muchos otros idiomas), la tensión imperativa se utiliza para dar órdenes. De forma similar, un estilo imperativo en la programación es aquel que le da a la computadora un conjunto de sentencias para llevar a cabo una tarea. -Often the statements change the state of the program, like updating global variables. A classic example is writing a `for` loop that gives exact directions to iterate over the indices of an array. +A menudo las sentencias cambian el estado del programa, como actualizar variables globales. Un ejemplo clásico es escribir un bucle `for` que dé instrucciones exactas para iterar sobre los índices de un arreglo. -In contrast, functional programming is a form of declarative programming. You tell the computer what you want done by calling a method or function. +Por el contrario, la programación funcional es una forma de programación declarativa. Le dice al ordenador lo que quieres hacer llamando a un método o función. -JavaScript offers many predefined methods that handle common tasks so you don't need to write out how the computer should perform them. For example, instead of using the `for` loop mentioned above, you could call the `map` method which handles the details of iterating over an array. This helps to avoid semantic errors, like the "Off By One Errors" that were covered in the Debugging section. +JavaScript ofrece muchos métodos predefinidos que manejan tareas comunes para que no necesites escribir cómo debe ejecutarlas el equipo. Por ejemplo, en lugar de usar el bucle `for` mencionado anteriormente se podría llamar al método `map` que maneja los detalles de iteración sobre un array. Esto ayuda a evitar errores semánticos, como los "Off By One Errors" que fueron cubiertos en la sección Debugging. -Consider the scenario: you are browsing the web in your browser, and want to track the tabs you have opened. Let's try to model this using some simple object-oriented code. +Considere el escenario: está navegando por la web en su navegador y quiere rastrear las pestañas que ha abierto. Intentemos modelar esto con un código simple orientado a objetos. -A Window object is made up of tabs, and you usually have more than one Window open. The titles of each open site in each Window object is held in an array. After working in the browser (opening new tabs, merging windows, and closing tabs), you want to print the tabs that are still open. Closed tabs are removed from the array and new tabs (for simplicity) get added to the end of it. +Un objeto ventana está formado por pestañas y normalmente tienes más de una abierta. Los títulos de cada sitio abierto en cada objeto ventana se mantienen en un arreglo. Después de trabajar en el navegador (abriendo nuevas pestañas, combinando ventanas y cerrando pestañas), deseas imprimir las pestañas que todavía están abiertas. Las pestañas cerradas se eliminan de la matriz y las nuevas pestañas (por simplicidad) se añaden al final de la misma. -The code editor shows an implementation of this functionality with functions for `tabOpen()`, `tabClose()`, and `join()`. The array `tabs` is part of the Window object that stores the name of the open pages. +El editor de código muestra una implementación de esta funcionalidad con funciones para `tabOpen()`, `tabClose()`y `join()`. El array `tabs` es parte del objeto ventana que almacena el nombre de las páginas abiertas. # --instructions-- -Examine the code in the editor. It's using a method that has side effects in the program, causing incorrect behaviour. The final list of open tabs, stored in `finalTabs.tabs`, should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` but the list produced by the code is slightly different. +Examine el código en el editor. Está utilizando un método que tiene efectos secundarios en el programa, causando un comportamiento incorrecto. La lista final de pestañas abiertas, almacenadas en `finalTabs.tabs` deberia ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` pero la lista producida por el código es un poco diferente. -Change `Window.prototype.tabClose` so that it removes the correct tab. +Cambia `Window.prototype.tabClose` para que elimine la pestaña correcta. # --hints-- -`finalTabs.tabs` should be `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` +`finalTabs.tabs` deberia ser `['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab']` ```js assert.deepEqual(finalTabs.tabs, [ diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.md index 4e63ab1df3..7e746cd33c 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.md @@ -1,6 +1,6 @@ --- id: 587d7dab367417b2b2512b6e -title: Use the every Method to Check that Every Element in an Array Meets a Criteria +title: Usa el método "every" para comprobar que cada elemento de un arreglo atienda un criterio challengeType: 1 forumTopicId: 301312 dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria @@ -8,43 +8,44 @@ dashedName: use-the-every-method-to-check-that-every-element-in-an-array-meets-a # --description-- -The `every` method works with arrays to check if *every* element passes a particular test. It returns a Boolean value - `true` if all values meet the criteria, `false` if not. +El método `every` funciona con arreglos para comprobar si *every element* pasa una prueba en particular. Devuelve un valor booleano - `true` si todos los valores cumplen los criterios, `false` si no. -For example, the following code would check if every element in the `numbers` array is less than 10: +Por ejemplo, el siguiente código comprobaría si cada elemento en el arreglo `numbers` es menor a 10: ```js var numbers = [1, 5, 8, 0, 10, 11]; numbers.every(function(currentValue) { return currentValue < 10; }); -// Returns false ``` +El método `every` devolvería `false` aquí. + # --instructions-- -Use the `every` method inside the `checkPositive` function to check if every element in `arr` is positive. The function should return a Boolean value. +Utiliza el método `every` dentro de la función `checkPositive` para comprobar si cada elemento en `arr` es positivo. La función debe devolver un valor booleano. # --hints-- -Your code should use the `every` method. +Tu código debe usar el método `every`. ```js assert(code.match(/\.every/g)); ``` -`checkPositive([1, 2, 3, -4, 5])` should return `false`. +`checkPositive([1, 2, 3, -4, 5])` debe devolver `false`. ```js assert.isFalse(checkPositive([1, 2, 3, -4, 5])); ``` -`checkPositive([1, 2, 3, 4, 5])` should return `true`. +`checkPositive([1, 2, 3, 4, 5])` debe devolver `true`. ```js assert.isTrue(checkPositive([1, 2, 3, 4, 5])); ``` -`checkPositive([1, -2, 3, -4, 5])` should return `false`. +`checkPositive([1, -2, 3, -4, 5])` debe devolver `false`. ```js assert.isFalse(checkPositive([1, -2, 3, -4, 5])); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.md index 0942be3924..bb073e9604 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.md @@ -1,6 +1,6 @@ --- id: 587d7b8f367417b2b2512b63 -title: Use the filter Method to Extract Data from an Array +title: Usa el método de "filter" para extraer datos de un arreglo challengeType: 1 forumTopicId: 18179 dashedName: use-the-filter-method-to-extract-data-from-an-array @@ -8,13 +8,13 @@ dashedName: use-the-filter-method-to-extract-data-from-an-array # --description-- -Another useful array function is `Array.prototype.filter()`, or simply `filter()`. +Otra función útil de los arreglos es `Array.prototype.filter()` o simplemente `filter()`. -`filter` calls a function on each element of an array and returns a new array containing only the elements for which that function returns `true`. In other words, it filters the array, based on the function passed to it. Like `map`, it does this without needing to modify the original array. +`filter` llama a una función en cada elemento de un arreglo y devuelve un nuevo arreglo que contiene solo los elementos por lo que esa función devuelve `true`. En otras palabras, filtra el arreglo, basándose en la función que se le pasa. Al igual que `map`, hace esto sin necesidad de modificar el arreglo original. -The callback function accepts three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `filter` method was called. +La función callback acepta tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo sobre el que se llamó al método `filter`. -See below for an example using the `filter` method on the `users` array to return a new array containing only the users under the age of 30. For simplicity, the example only uses the first argument of the callback. +A continuación se muestra un ejemplo en el que se utiliza el método `filter` en el arreglo `users` para devolver un nuevo arreglo que contiene sólo a los usuarios menores de 30 años. Para que sea más fácil, el ejemplo sólo utiliza el primer argumento del callback. ```js const users = [ @@ -24,16 +24,18 @@ const users = [ ]; const usersUnder30 = users.filter(user => user.age < 30); -console.log(usersUnder30); // [ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ] +console.log(usersUnder30); ``` +La consola muestra el valor `[ { name: 'Amy', age: 20 }, { name: 'camperCat', age: 10 } ]`. + # --instructions-- -The variable `watchList` holds an array of objects with information on several movies. Use a combination of `filter` and `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys. The new array should only include objects where `imdbRating` is greater than or equal to 8.0. Note that the rating values are saved as strings in the object and you may need to convert them into numbers to perform mathematical operations on them. +La variable `watchList` contiene un arreglo de objetos con información sobre varias películas. Utiliza una combinación de `filter` y `map` en `watchList` para asignar un nuevo arreglo de objetos con solo `title` y `rating` claves. El nuevo arreglo solo debe incluir objetos donde `imdbRating` es mayor o igual a 8.0. Ten en cuenta que los valores `rating` se guardan como cadenas en el objeto y puedes necesitar convertirlos en números para realizar operaciones matemáticas en ellos. # --hints-- -The `watchList` variable should not change. +La variable `watchList` no debe cambiar. ```js assert( @@ -41,19 +43,19 @@ assert( ); ``` -Your code should use the `filter` method. +Tu código debe usar el método `filter`. ```js assert(code.match(/\.filter/g)); ``` -Your code should not use a `for` loop. +El código no debe utilizar el bucle `for`. ```js assert(!code.match(/for\s*?\([\s\S]*?\)/g)); ``` -`filteredList` should equal `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`. +`filteredList` debe ser igual a `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`. ```js assert.deepEqual(filteredList, [ diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.md index 0ddd1c3d56..6f48837fa4 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.md @@ -1,6 +1,6 @@ --- id: 587d7b8f367417b2b2512b61 -title: Use the map Method to Extract Data from an Array +title: Usa el método "map" para extraer datos de un arreglo challengeType: 1 forumTopicId: 18214 dashedName: use-the-map-method-to-extract-data-from-an-array @@ -8,19 +8,19 @@ dashedName: use-the-map-method-to-extract-data-from-an-array # --description-- -So far we have learned to use pure functions to avoid side effects in a program. Also, we have seen the value in having a function only depend on its input arguments. +Hasta ahora hemos aprendido a utilizar funciones puras para evitar efectos secundarios en un programa. Además, hemos aprendido el valor de tener una función que solo depende de sus argumentos de entrada. -This is only the beginning. As its name suggests, functional programming is centered around a theory of functions. +Este es solo el principio. Como su nombre indica, la programación funcional se centra en una teoría de funciones. -It would make sense to be able to pass them as arguments to other functions, and return a function from another function. Functions are considered first class objects in JavaScript, which means they can be used like any other object. They can be saved in variables, stored in an object, or passed as function arguments. +Tendría sentido pasarlos como argumentos a otras funciones y devolver una función de otra función. Las funciones se consideran first class objects en JavaScript, lo que significa que pueden ser usados como cualquier otro objeto. Pueden guardarse en variables, almacenarse en un objeto o pasarse como argumentos de función. -Let's start with some simple array functions, which are methods on the array object prototype. In this exercise we are looking at `Array.prototype.map()`, or more simply `map`. +Empecemos con algunas funciones de arreglos simples, que son métodos en el prototipo de objetos del arreglo. En este ejercicio estamos utilizando `Array.prototype.map()` o más específicamente `map`. -The `map` method iterates over each item in an array and returns a new array containing the results of calling the callback function on each element. It does this without mutating the original array. +El método `map` iterará sobre cada elemento de un arreglo y devuelve un nuevo arreglo que contiene los resultados de llamar a la función callback en cada elemento. Esto lo hace sin mutar el arreglo original. -When the callback is used, it is passed three arguments. The first argument is the current element being processed. The second is the index of that element and the third is the array upon which the `map` method was called. +Cuando se utiliza el callback, se pasan tres argumentos. El primer argumento es el elemento actual que se está procesando. El segundo es el índice de ese elemento y el tercero es el arreglo al que se llamó el método `map`. -See below for an example using the `map` method on the `users` array to return a new array containing only the names of the users as elements. For simplicity, the example only uses the first argument of the callback. +A continuación se muestra un ejemplo con el método `map` en el arreglo `users` para devolver un nuevo arreglo que contiene solo los nombres de los usuarios como elementos. Para que sea más fácil, el ejemplo solo utiliza el primer argumento del callback. ```js const users = [ @@ -30,16 +30,18 @@ const users = [ ]; const names = users.map(user => user.name); -console.log(names); // [ 'John', 'Amy', 'camperCat' ] +console.log(names); ``` +La consola mostraría el valor `[ 'John', 'Amy', 'camperCat' ]`. + # --instructions-- -The `watchList` array holds objects with information on several movies. Use `map` on `watchList` to assign a new array of objects with only `title` and `rating` keys to the `ratings` variable. The code in the editor currently uses a `for` loop to do this, so you should replace the loop functionality with your `map` expression. +El arreglo `watchList` contiene objetos con información sobre varias películas. Usa `map` en `watchList` para asignar un nuevo arreglo de objetos con solo `title` y `rating` claves a la variable `ratings`. El código en el editor utiliza actualmente un bucle `for` para hacer esto, por lo que debería reemplazar la funcionalidad del bucle con su expresión `map`. # --hints-- -The `watchList` variable should not change. +La variable `watchList` no debe cambiar. ```js assert( @@ -47,19 +49,19 @@ assert( ); ``` -Your code should not use a `for` loop. +Tu código no debe usar un bucle `for`. ```js assert(!__helpers.removeJSComments(code).match(/for\s*?\([\s\S]*?\)/)); ``` -Your code should use the `map` method. +Tu código debe usar el método `map`. ```js assert(code.match(/\.map/g)); ``` -`ratings` should equal `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`. +`ratings` debe ser igual a `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`. ```js assert.deepEqual(ratings, [ diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.md index f9a80004a4..3208d3d5bf 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.md @@ -1,6 +1,6 @@ --- id: 587d7da9367417b2b2512b68 -title: Use the reduce Method to Analyze Data +title: Utiliza el método "reduce" para analizar datos challengeType: 1 forumTopicId: 301313 dashedName: use-the-reduce-method-to-analyze-data @@ -8,15 +8,15 @@ dashedName: use-the-reduce-method-to-analyze-data # --description-- -`Array.prototype.reduce()`, or simply `reduce()`, is the most general of all array operations in JavaScript. You can solve almost any array processing problem using the `reduce` method. +`Array.prototype.reduce()` o simplemente `reduce()` es la operación más común de todas para arreglos en JavaScript. Se puede resolver casi cualquier problema de procesamiento de arreglos utilizando el método `reduce`. -The `reduce` method allows for more general forms of array processing, and it's possible to show that both `filter` and `map` can be derived as special applications of `reduce`. The `reduce` method iterates over each item in an array and returns a single value (i.e. string, number, object, array). This is achieved via a callback function that is called on each iteration. +El método `reduce` permite formas más generales de procesamiento de arreglos y es posible mostrar que tanto `filter` como `map` pueden derivarse como aplicaciones especiales de `reduce`. El método `reduce` itera sobre cada elemento del arreglo y devuelve un solo valor (por ejemplo una cadena, número, objeto, arreglo). Esto se consigue mediante una función de callback que se llama en cada iteración. -The callback function accepts four arguments. The first argument is known as the accumulator, which gets assigned the return value of the callback function from the previous iteration, the second is the current element being processed, the third is the index of that element and the fourth is the array upon which `reduce` is called. +La función callback acepta cuatro argumentos. El primer argumento se conoce como acumulador, que recibe el valor retornado de la función callback de la iteración anterior, el segundo es el elemento actual que se está procesando, el tercero es el índice de ese elemento y el cuarto es el arreglo sobre el que se llama a la función `reduce`. -In addition to the callback function, `reduce` has an additional parameter which takes an initial value for the accumulator. If this second parameter is not used, then the first iteration is skipped and the second iteration gets passed the first element of the array as the accumulator. +Además de la función callback, `reduce` tiene un parámetro adicional que toma un valor inicial para el acumulador. Si este segundo parámetro no se utiliza, entonces la primera iteración se omite y la segunda se pasa por el primer elemento del arreglo como acumulador. -See below for an example using `reduce` on the `users` array to return the sum of all the users' ages. For simplicity, the example only uses the first and second arguments. +Mira a continuación un ejemplo con `reduce` en el arreglo `users` para devolver la suma de todas las edades de los usuarios. Para hacerlo más fácil, el ejemplo sólo utiliza el primer y segundo argumento. ```js const users = [ @@ -26,10 +26,12 @@ const users = [ ]; const sumOfAges = users.reduce((sum, user) => sum + user.age, 0); -console.log(sumOfAges); // 64 +console.log(sumOfAges); ``` -In another example, see how an object can be returned containing the names of the users as properties with their ages as values. +La consola mostrará el valor `64`. + +En otro ejemplo, se puede observar cómo un objeto puede ser devuelto con los nombres de los usuarios como propiedades con las edades como valores. ```js const users = [ @@ -42,16 +44,18 @@ const usersObj = users.reduce((obj, user) => { obj[user.name] = user.age; return obj; }, {}); -console.log(usersObj); // { John: 34, Amy: 20, camperCat: 10 } +console.log(usersObj); ``` +La consola mostrará el valor `{ John: 34, Amy: 20, camperCat: 10 }`. + # --instructions-- -The variable `watchList` holds an array of objects with information on several movies. Use `reduce` to find the average IMDB rating of the movies **directed by Christopher Nolan**. Recall from prior challenges how to `filter` data and `map` over it to pull what you need. You may need to create other variables, and return the average rating from `getRating` function. Note that the rating values are saved as strings in the object and need to be converted into numbers before they are used in any mathematical operations. +La variable `watchList` contiene un arreglo de objetos con información sobre varias películas. Utiliza `reduce` para encontrar la calificación media en IMDB de las películas dirigidas por `Christopher Nolan`. Recuerda de desafíos anteriores filtrar (`filter`) los datos y mapear (`map`) sobre ellos para extraer lo que necesitas. Puede que necesites crear otras variables y devolver la calificación media con la función `getRating`. Ten en cuenta que los valores de calificación se guardan como cadenas en el objeto y necesitan ser convertidos en números antes de ser utilizados en cualquier operación matemática. # --hints-- -The `watchList` variable should not change. +La variable `watchList` no debe cambiar. ```js assert( @@ -59,25 +63,25 @@ assert( ); ``` -Your code should use the `reduce` method. +Tu código debe utilizar el método `reduce`. ```js assert(code.match(/\.reduce/g)); ``` -The `getRating(watchList)` should equal 8.675. +`getRating(watchList)` debe ser igual a 8.675. ```js assert(getRating(watchList) === 8.675); ``` -Your code should not use a `for` loop. +Tu código no debe usar un bucle `for`. ```js assert(!code.match(/for\s*?\([\s\S]*?\)/g)); ``` -Your code should return correct output after modifying the `watchList` object. +Tu código debe devolver el resultado correcto después de modificar el objeto `watchList`. ```js assert(getRating(watchList.filter((_, i) => i < 1 || i > 2)) === 8.55); diff --git a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.md b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.md index 3aa85c4dab..efeffa6c6c 100644 --- a/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.md +++ b/curriculum/challenges/espanol/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.md @@ -1,6 +1,6 @@ --- id: 587d7dab367417b2b2512b6f -title: Use the some Method to Check that Any Elements in an Array Meet a Criteria +title: Usa el método "some" para comprobar si algún elemento en un arreglo cumple un criterio challengeType: 1 forumTopicId: 301314 dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria @@ -8,43 +8,44 @@ dashedName: use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-cr # --description-- -The `some` method works with arrays to check if *any* element passes a particular test. It returns a Boolean value - `true` if any of the values meet the criteria, `false` if not. +El método `some` funciona con arreglos para comprobar si *algún* elemento pasa una prueba en particular. Devuelve un valor booleano `true` si alguno de los valores cumple el criterio, `false` si no. -For example, the following code would check if any element in the `numbers` array is less than 10: +Por ejemplo, el siguiente código comprobará si algún elemento en el arreglo `numbers` es menor que 10: ```js var numbers = [10, 50, 8, 220, 110, 11]; numbers.some(function(currentValue) { return currentValue < 10; }); -// Returns true ``` +El método `some` devolverá `true`. + # --instructions-- -Use the `some` method inside the `checkPositive` function to check if any element in `arr` is positive. The function should return a Boolean value. +Utiliza el método `some` dentro de la función `checkPositive` para comprobar si algún elemento en `arr` es positivo. La función debe devolver un valor booleano. # --hints-- -Your code should use the `some` method. +Tu código debe usar el método `some`. ```js assert(code.match(/\.some/g)); ``` -`checkPositive([1, 2, 3, -4, 5])` should return `true`. +`checkPositive([1, 2, 3, -4, 5])` debe devolver `true`. ```js assert(checkPositive([1, 2, 3, -4, 5])); ``` -`checkPositive([1, 2, 3, 4, 5])` should return `true`. +`checkPositive([1, 2, 3, 4, 5])` debe devolver `true`. ```js assert(checkPositive([1, 2, 3, 4, 5])); ``` -`checkPositive([-1, -2, -3, -4, -5])` should return `false`. +`checkPositive([-1, -2, -3, -4, -5])` debe devolver `false`. ```js assert(!checkPositive([-1, -2, -3, -4, -5]));