diff --git a/curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/meta.json b/curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/meta.json deleted file mode 100644 index dce6b46e84..0000000000 --- a/curriculum/challenges/english/04-data-visualization/data-visualization-with-d3/meta.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "name": "Data Visualization with D3", - "dashedName": "data-visualization-with-d3", - "order": 1, - "time": "5 hours", - "template": "", - "required": [], - "superBlock": "data-visualization", - "superOrder": 4, - "challengeOrder": [ - [ - "587d7fa6367417b2b2512bc2", - "Add Document Elements with D3" - ], - [ - "587d7fa6367417b2b2512bc3", - "Select a Group of Elements with D3" - ], - [ - "587d7fa7367417b2b2512bc4", - "Work with Data in D3" - ], - [ - "587d7fa7367417b2b2512bc5", - "Work with Dynamic Data in D3" - ], - [ - "587d7fa7367417b2b2512bc6", - "Add Inline Styling to Elements" - ], - [ - "587d7fa7367417b2b2512bc7", - "Change Styles Based on Data" - ], - [ - "587d7fa7367417b2b2512bc8", - "Add Classes with D3" - ], - [ - "587d7fa8367417b2b2512bc9", - "Update the Height of an Element Dynamically" - ], - [ - "587d7fa8367417b2b2512bca", - "Change the Presentation of a Bar Chart" - ], - [ - "587d7fa8367417b2b2512bcb", - "Learn About SVG in D3" - ], - [ - "587d7fa8367417b2b2512bcc", - "Display Shapes with SVG" - ], - [ - "587d7fa8367417b2b2512bcd", - "Create a Bar for Each Data Point in the Set" - ], - [ - "587d7fa9367417b2b2512bce", - "Dynamically Set the Coordinates for Each Bar" - ], - [ - "587d7fa9367417b2b2512bcf", - "Dynamically Change the Height of Each Bar" - ], - [ - "587d7fa9367417b2b2512bd0", - "Invert SVG Elements" - ], - [ - "587d7fa9367417b2b2512bd1", - "Change the Color of an SVG Element" - ], - [ - "587d7faa367417b2b2512bd2", - "Add Labels to D3 Elements" - ], - [ - "587d7faa367417b2b2512bd3", - "Style D3 Labels" - ], - [ - "587d7faa367417b2b2512bd4", - "Add a Hover Effect to a D3 Element" - ], - [ - "587d7faa367417b2b2512bd6", - "Add a Tooltip to a D3 Element" - ], - [ - "587d7fab367417b2b2512bd7", - "Create a Scatterplot with SVG Circles" - ], - [ - "587d7fab367417b2b2512bd8", - "Add Attributes to the Circle Elements" - ], - [ - "587d7fab367417b2b2512bd9", - "Add Labels to Scatter Plot Circles" - ], - [ - "587d7fab367417b2b2512bda", - "Create a Linear Scale with D3" - ], - [ - "587d7fac367417b2b2512bdb", - "Set a Domain and a Range on a Scale" - ], - [ - "587d7fac367417b2b2512bdc", - "Use the d3.max and d3.min Functions to Find Minimum and Maximum Values in a Dataset" - ], - [ - "587d7fac367417b2b2512bdd", - "Use Dynamic Scales" - ], - [ - "587d7fac367417b2b2512bde", - "Use a Pre-Defined Scale to Place Elements" - ], - [ - "587d7fad367417b2b2512bdf", - "Add Axes to a Visualization" - ] - ], - "helpRoom": "Help", - "fileName": "04-data-visualization/data-visualization-with-d3.json" -} \ No newline at end of file diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-a-text-alternative-to-images-for-visually-impaired-accessibility.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-a-text-alternative-to-images-for-visually-impaired-accessibility.spanish.md new file mode 100644 index 0000000000..6f224dc930 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-a-text-alternative-to-images-for-visually-impaired-accessibility.spanish.md @@ -0,0 +1,56 @@ +--- +id: 587d774c367417b2b2512a9c +title: Add a Text Alternative to Images for Visually Impaired Accessibility +localeTitle: Agregar una alternativa de texto a las imágenes para la accesibilidad de personas con discapacidad visual +challengeType: 0 +videoUrl: '' +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-alt-text-to-an-image-for-accessibility' +--- + +## Description +
+Es probable que haya visto un atributo alt en una etiqueta img en otros desafíos. Alt texto alternativo describe el contenido de la imagen y proporciona una alternativa de texto. Esto ayuda en caso de que la imagen no se cargue o no pueda ser vista por un usuario. También es utilizado por los motores de búsqueda para comprender qué contiene una imagen para incluirla en los resultados de búsqueda. Aquí hay un ejemplo: +<img src="importantLogo.jpeg" alt="Company logo"> +personas con discapacidades visuales confían en los lectores de pantalla para convertir el contenido web a una interfaz de audio. No obtendrán información si solo se presenta visualmente. Para las imágenes, los lectores de pantalla pueden acceder al atributo alt y leer su contenido para entregar información clave. +buen texto alt es breve pero descriptivo, y está pensado para transmitir brevemente el significado de la imagen. Siempre debes incluir un atributo alt en tu imagen. Por especificación de HTML5, esto ahora se considera obligatorio. +
+ +## Instructions +
+Camper Cat es tanto un ninja codificador como un ninja real, y está construyendo un sitio web para compartir sus conocimientos. La imagen de perfil que desea usar muestra sus habilidades y debe ser apreciada por todos los visitantes del sitio. Agregue un atributo alt en la etiqueta img , que explica que Camper Cat está haciendo karate. (La imagen src no se vincula a un archivo real, por lo que debería ver el texto alt en la pantalla). +
+ +## Tests +
+ +```yml +tests: + - text: 'Su etiqueta img debe tener un atributo alt , y no debe estar vacío'. + testString: 'assert($("img").attr("alt"), "Your img tag should have an alt attribute, and it should not be empty.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-an-accessible-date-picker.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-an-accessible-date-picker.spanish.md new file mode 100644 index 0000000000..d3d2a7e817 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/add-an-accessible-date-picker.spanish.md @@ -0,0 +1,84 @@ +--- +id: 587d778b367417b2b2512aa8 +title: Add an Accessible Date Picker +localeTitle: Añadir un selector de fecha accesible +challengeType: 0 +videoUrl: '' +--- + +## Description +
+formularios a menudo incluyen el campo de input , que se puede usar para crear varios controles de formulario diferentes. El atributo de type en este elemento indica qué tipo de entrada se creará. +Usted puede haber notado el text y submit los tipos de entrada en los desafíos anteriores, y HTML5 introducido una opción para especificar una date campo. Dependiendo de la compatibilidad del navegador, un selector de fecha aparece en el campo de input cuando está enfocado, lo que facilita el llenado de un formulario para todos los usuarios. +Para los navegadores más antiguos, el tipo será el text predeterminado, por lo que es útil mostrar a los usuarios el formato de fecha esperado en la etiqueta o como texto de marcador de posición, por si acaso. +Aquí hay un ejemplo: +
<label for="input1">Enter a date:</label>
<input type="date" id="input1" name="input1">
+
+ +## Instructions +
+Camper Cat está organizando un torneo de Mortal Kombat y quiere preguntar a sus competidores para ver qué fecha funciona mejor. Agregue una etiqueta de input con un atributo de type de "fecha", un atributo de id de "pickdate" y un atributo de name de "fecha". +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una etiqueta de input para el campo selector de fecha. + testString: 'assert($("input").length == 2, "Your code should add one input tag for the date selector field.");' + - text: Su etiqueta de input debe tener un atributo de type con un valor de fecha. + testString: 'assert($("input").attr("type") == "date", "Your input tag should have a type attribute with a value of date.");' + - text: Su etiqueta de input debe tener un atributo id con un valor de pickdate. + testString: 'assert($("input").attr("id") == "pickdate", "Your input tag should have an id attribute with a value of pickdate.");' + - text: Su etiqueta de input debe tener un atributo de name con un valor de fecha. + testString: 'assert($("input").attr("name") == "date", "Your input tag should have a name attribute with a value of date.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Tournaments

+
+
+
+

Mortal Kombat Tournament Survey

+
+

Tell us the best date for the competition

+ + + + + + + + + +
+
+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-carefully-choosing-colors-that-convey-information.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-carefully-choosing-colors-that-convey-information.spanish.md new file mode 100644 index 0000000000..2d28c617af --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-carefully-choosing-colors-that-convey-information.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d778f367417b2b2512aad +title: Avoid Colorblindness Issues by Carefully Choosing Colors that Convey Information +localeTitle: Evite los problemas de ceguera al color al elegir cuidadosamente los colores que transmiten información +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hay varias formas de ceguera al color. Estos pueden ir desde una sensibilidad reducida hasta una cierta longitud de onda de la luz hasta la incapacidad de ver el color. La forma más común es una sensibilidad reducida para detectar greens. +Por ejemplo, si dos colores verdes similares son el color de primer plano y de fondo de su contenido, es posible que un usuario que no tenga color no pueda distinguirlos. Los colores cercanos pueden considerarse vecinos de la rueda de colores, y deben evitarse esas combinaciones cuando se transmite información importante. +Nota
Algunas herramientas de selección de color en línea incluyen simulaciones visuales de cómo aparecen los colores para diferentes tipos de ceguera al color. Estos son excelentes recursos además de las calculadoras de comprobación de contraste en línea. +
+ +## Instructions +
+Camper Cat está probando diferentes estilos para un botón importante, pero el color de background-color amarillo ( #FFFF33 ) y el color verde ( #33FF33 ) son tonalidades #33FF33 en la rueda de colores y prácticamente no se distinguen para algunos usuarios con #33FF33 color . (Su luminosidad similar también falla la comprobación de la relación de contraste). Cambie el color del texto a azul oscuro ( #003366 ) para resolver ambos problemas. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe cambiar el color del texto del button a azul oscuro. + testString: 'assert($("button").css("color") == "rgb(0, 51, 102)", "Your code should change the text color for the button to the dark blue.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Danger!

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-using-sufficient-contrast.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-using-sufficient-contrast.spanish.md new file mode 100644 index 0000000000..7f445b9ad6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/avoid-colorblindness-issues-by-using-sufficient-contrast.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d778f367417b2b2512aac +title: Avoid Colorblindness Issues by Using Sufficient Contrast +localeTitle: Evite los problemas de ceguera al color usando un contraste suficiente +challengeType: 0 +videoUrl: '' +--- + +## Description +
+color es una gran parte del diseño visual, pero su uso presenta dos problemas de accesibilidad. Primero, el color solo no debe usarse como la única forma de transmitir información importante porque los usuarios de lectores de pantalla no la verán. En segundo lugar, los colores de fondo y de fondo necesitan un contraste suficiente para que los usuarios con daltonismo los puedan distinguir. +Los desafíos anteriores cubrieron tener alternativas de texto para abordar el primer problema. El último desafío introdujo herramientas de comprobación de contraste para ayudar con el segundo. La relación de contraste recomendada por WCAG de 4.5: 1 se aplica al uso del color así como a las combinaciones de escala de grises. +usuarios de Colorblind tienen problemas para distinguir algunos colores de otros, generalmente en tonos, pero a veces también con ligereza. Puede recordar que la relación de contraste se calcula utilizando los valores de luminancia relativa (o luminosidad) de los colores de primer plano y de fondo. +En la práctica, se puede alcanzar la proporción de 4.5: 1 oscureciendo el color más oscuro y aclarando el más claro con la ayuda de un comprobador de contraste de color. Los colores más oscuros en la rueda de colores se consideran azules, violetas, magentas y rojos, mientras que los colores más claros son naranjas, amarillos, verdes y verdes azules. +
+ +## Instructions +
+Camper gato está experimentando con el uso del color para su blog de texto y el fondo, pero su actual combinación de un color verdoso background-color con el texto marrón color tiene un 2.5: 1 relación de contraste. Puede ajustar fácilmente la luminosidad de los colores ya que los declaró utilizando la propiedad hsl() CSS (que significa matiz, saturación, luminosidad) cambiando el tercer argumento. Aumente el valor de luminosidad del background-color del 35% al ​​55% y disminuya el valor de luminosidad del color del 20% al 15%. Esto mejora el contraste a 5.9: 1. +
+ +## Tests +
+ +```yml +tests: + - text: Su código solo debe cambiar el valor de luminosidad de la propiedad de color del texto a un valor del 15%. + testString: 'assert(code.match(/color:\s*?hsl\(0,\s*?55%,\s*?15%\)/gi), "Your code should only change the lightness value for the text color property to a value of 15%.");' + - text: Su código solo debe cambiar el valor de luminosidad de la propiedad de background-color a un valor del 55%. + testString: 'assert(code.match(/background-color:\s*?hsl\(120,\s*?25%,\s*?55%\)/gi), "Your code should only change the lightness value for the background-color property to a value of 55%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Deep Thoughts with Master Camper Cat

+
+
+

A Word on the Recent Catnip Doping Scandal

+

The influence that catnip has on feline behavior is well-documented, and its use as an herbal supplement in competitive ninja circles remains controversial. Once again, the debate to ban the substance is brought to the public's attention after the high-profile win of Kittytron, a long-time proponent and user of the green stuff, at the Claw of Fury tournament.

+

As I've stated in the past, I firmly believe a true ninja's skills must come from within, with no external influences. My own catnip use shall continue as purely recreational.

+
+ +``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "body {color: hsl(0, 55%, 15%); background-color: hsl(120, 25%, 55%);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/give-links-meaning-by-using-descriptive-link-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/give-links-meaning-by-using-descriptive-link-text.spanish.md new file mode 100644 index 0000000000..848009afa4 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/give-links-meaning-by-using-descriptive-link-text.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d778f367417b2b2512aae +title: Give Links Meaning by Using Descriptive Link Text +localeTitle: Dar el significado de enlaces mediante el uso de texto de enlace descriptivo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los usuarios de lectores de pantalla tienen diferentes opciones para el tipo de contenido que lee su dispositivo. Esto incluye saltar a (o sobre) elementos de hito, saltar al contenido principal u obtener un resumen de la página de los encabezados. Otra opción es escuchar solo los enlaces disponibles en una página. +Los lectores de pantalla hacen esto leyendo el texto del enlace, o lo que hay entre las etiquetas de ancla ( a ). Tener una lista de enlaces "haga clic aquí" o "leer más" no es útil. En su lugar, debe utilizar el texto breve pero descriptiva dentro de las a etiquetas para proporcionar más significado para estos usuarios. +
+ +## Instructions +
+El texto del enlace que está utilizando Camper Cat no es muy descriptivo sin el contexto que lo rodea. Mueva las etiquetas de anclaje ( a ) para que envuelvan el texto "información sobre baterías" en lugar de "Haga clic aquí". +
+ +## Tests +
+ +```yml +tests: + - text: El código debe mover el ancla a las etiquetas de todo las palabras "Haga clic aquí" para envolver alrededor de las palabras "información sobre las baterías". + testString: 'assert($("a").text().match(/^(information about batteries)$/g), "Your code should move the anchor a tags from around the words "Click here" to wrap around the words "information about batteries".");' + - text: Asegúrese de que su a elemento tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/a>/g) && code.match(/<\/a>/g).length === code.match(//g).length, "Make sure your a element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Deep Thoughts with Master Camper Cat

+
+
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-accessibility-of-audio-content-with-the-audio-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-accessibility-of-audio-content-with-the-audio-element.spanish.md new file mode 100644 index 0000000000..a97023638b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-accessibility-of-audio-content-with-the-audio-element.spanish.md @@ -0,0 +1,79 @@ +--- +id: 587d7789367417b2b2512aa4 +title: Improve Accessibility of Audio Content with the audio Element +localeTitle: Mejorar la accesibilidad del contenido de audio con el elemento de audio +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El elemento de audio de HTML5 da un significado semántico cuando envuelve el contenido de la transmisión de sonido o audio en su marca. El contenido de audio también necesita una alternativa de texto para que las personas sordas o con dificultades auditivas puedan acceder. Esto se puede hacer con el texto cercano en la página o un enlace a una transcripción. +La etiqueta de audio admite el atributo de controls . Esto muestra los controles de reproducción, pausa y otros controles predeterminados del navegador, y es compatible con la funcionalidad del teclado. Este es un atributo booleano, lo que significa que no necesita un valor, su presencia en la etiqueta activa la configuración. +Aquí hay un ejemplo: +
<audio id="meowClip" controls>
  <source src="audio/meow.mp3" type="audio/mpeg" />
  <source src="audio/meow.ogg" type="audio/ogg" />
</audio>
+Nota
El contenido multimedia suele tener componentes tanto visuales como auditivos. Necesita subtítulos sincronizados y una transcripción para que los usuarios con discapacidades visuales y / o auditivas puedan acceder a ella. Generalmente, un desarrollador web no es responsable de crear los subtítulos o la transcripción, pero necesita saber para incluirlos. +
+ +## Instructions +
+hora de tomar un descanso de Camper Cat y conocer a su compañero campista Zersiax (@zersiax), un campeón de accesibilidad y un usuario de lector de pantalla. Para escuchar un clip de su lector de pantalla en acción, agregue un elemento de audio después de la p . Incluir el atributo de controls . Luego coloque una etiqueta de source dentro de las etiquetas de audio con el atributo src configurado en "https://s3.amazonaws.com/freecodecamp/screen-reader.mp3" y type atributo establecido en "audio / mpeg". +Nota
El clip de audio puede sonar rápido y ser difícil de entender, pero esa es una velocidad normal para los usuarios de lectores de pantalla. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta de audio . + testString: 'assert($("audio").length === 1, "Your code should have one audio tag.");' + - text: Asegúrese de que su elemento de audio tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/audio>/g).length === 1 && code.match(/[\s\S]*<\/audio>/g), "Make sure your audio element has a closing tag.");' + - text: La etiqueta de audio debe tener el atributo de controls . + testString: 'assert($("audio").attr("controls"), "The audio tag should have the controls attribute.");' + - text: Su código debe tener una etiqueta de source . + testString: 'assert($("source").length === 1, "Your code should have one source tag.");' + - text: Su etiqueta de source debe estar dentro de las etiquetas de audio . + testString: 'assert($("audio").children("source").length === 1, "Your source tag should be inside the audio tags.");' + - text: El valor del atributo src en la etiqueta de source debe coincidir exactamente con el enlace en las instrucciones. + testString: 'assert($("source").attr("src") === "https://s3.amazonaws.com/freecodecamp/screen-reader.mp3", "The value for the src attribute on the source tag should match the link in the instructions exactly.");' + - text: Su código debe incluir un atributo de type en la etiqueta de source con un valor de audio / mpeg. + testString: 'assert($("source").attr("type") === "audio/mpeg", "Your code should include a type attribute on the source tag with a value of audio/mpeg.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Real Coding Ninjas

+
+
+

A sound clip of Zersiax's screen reader in action.

+ + + +
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-chart-accessibility-with-the-figure-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-chart-accessibility-with-the-figure-element.spanish.md new file mode 100644 index 0000000000..1578519329 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-chart-accessibility-with-the-figure-element.spanish.md @@ -0,0 +1,105 @@ +--- +id: 587d778a367417b2b2512aa5 +title: Improve Chart Accessibility with the figure Element +localeTitle: Mejora la accesibilidad de la carta con la figura Elemento. +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML5 introdujo el elemento figure , junto con la figcaption relacionada. Usados ​​juntos, estos elementos envuelven una representación visual (como una imagen, diagrama o gráfico) junto con su título. Esto proporciona un aumento de accesibilidad doble al agrupar semánticamente el contenido relacionado y al proporcionar una alternativa de texto que explica la figure . +Para visualizaciones de datos como cuadros, la leyenda se puede usar para observar brevemente las tendencias o conclusiones para usuarios con discapacidades visuales. Otro desafío es cómo mover una versión de tabla de los datos del gráfico fuera de la pantalla (mediante CSS) para los usuarios de lectores de pantalla. +Aquí hay un ejemplo: tenga en cuenta que la figcaption va dentro de las etiquetas de figure y se puede combinar con otros elementos: +
<figure>
  <img src="roundhouseDestruction.jpeg" alt="Photo of Camper Cat executing a roundhouse kick">
  <br>
  <figcaption>
    Master Camper Cat demonstrates proper form of a roundhouse kick.
  </figcaption>
</figure>
+
+ +## Instructions +
+Camper Cat está trabajando duro para crear un gráfico de barras apiladas que muestre la cantidad de tiempo por semana para pasar el entrenamiento en sigilo, combate y armas. Ayúdelo a estructurar mejor su página cambiando la etiqueta div que usó por una etiqueta de figure , y la etiqueta p que rodea el título a una etiqueta de figcaption . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta de figure . + testString: 'assert($("figure").length == 1, "Your code should have one figure tag.");' + - text: Su código debe tener una etiqueta de figcaption . + testString: 'assert($("figcaption").length == 1, "Your code should have one figcaption tag.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + - text: Su código no debe tener ninguna etiqueta p . + testString: 'assert($("p").length == 0, "Your code should not have any p tags.");' + - text: La figcaption debe ser un hijo de la etiqueta de la figure . + testString: 'assert($("figure").children("figcaption").length == 1, "The figcaption should be a child of the figure tag.");' + - text: Asegúrese de que el elemento de su figure tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/figure>/g) && code.match(/<\/figure>/g).length === code.match(/
/g).length, "Make sure your figure element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Training

+ +
+
+
+ + +
+ +
+

Breakdown per week of time to spend training in stealth, combat, and weapons.

+
+ + +
+
+

Stealth & Agility Training

+

Climb foliage quickly using a minimum spanning tree approach

+

No training is NP-complete without parkour

+
+
+

Combat Training

+

Dispatch multiple enemies with multithreaded tactics

+

Goodbye world: 5 proven ways to knock out an opponent

+
+
+

Weapons Training

+

Swords: the best tool to literally divide and conquer

+

Breadth-first or depth-first in multi-weapon training?

+
+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-form-field-accessibility-with-the-label-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-form-field-accessibility-with-the-label-element.spanish.md new file mode 100644 index 0000000000..f25bd6f255 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-form-field-accessibility-with-the-label-element.spanish.md @@ -0,0 +1,89 @@ +--- +id: 587d778a367417b2b2512aa6 +title: Improve Form Field Accessibility with the label Element +localeTitle: Mejorar la accesibilidad del campo de formulario con la etiqueta Elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+mejora de la accesibilidad con el código HTML semántico se aplica al uso de nombres de etiquetas y atributos apropiados. Los siguientes varios desafíos cubren algunos escenarios importantes utilizando atributos en formularios. +La label etiqueta envuelve el texto de un elemento de control de formulario específico, generalmente el nombre o la etiqueta de una opción. Esto vincula el significado al elemento y hace que la forma sea más legible. El atributo for en una label etiqueta asocia explícitamente esa label con el control de formulario y es utilizado por los lectores de pantalla. +Aprendió sobre los botones de radio y sus etiquetas en una lección en la sección HTML básico. En esa lección, envolvimos el elemento de entrada del botón de radio dentro de un elemento de label junto con el texto de la etiqueta para poder hacer clic en el texto. Otra forma de lograr esto es utilizando el atributo for como se explica en esta lección. +El valor del atributo for debe ser el mismo que el valor del atributo id del control de formulario. Aquí hay un ejemplo: +
<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
</form>
+
+ +## Instructions +
+Camper Cat espera mucho interés en las publicaciones de su blog, y desea incluir un formulario de registro por correo electrónico. Agregue un atributo for en la label correo electrónico que coincida con el id en su campo de input . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener un atributo for en la label etiqueta que no esté vacía. + testString: 'assert($("label").attr("for"), "Your code should have a for attribute on the label tag that is not empty.");' + - text: El valor del atributo for debe coincidir con el valor de id en la input correo electrónico. + testString: 'assert($("label").attr("for") == "email", "Your for attribute value should match the id value on the email input.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Deep Thoughts with Master Camper Cat

+
+
+
+

Sign up to receive Camper Cat's blog posts by email here!

+ + + + + + + +
+
+
+

The Garfield Files: Lasagna as Training Fuel?

+

The internet is littered with varying opinions on nutritional paradigms, from catnip paleo to hairball cleanses. But let's turn our attention to an often overlooked fitness fuel, and examine the protein-carb-NOM trifecta that is lasagna...

+
+ +
+

Defeating your Foe: the Red Dot is Ours!

+

Felines the world over have been waging war on the most persistent of foes. This red nemesis combines both cunning stealth and lightening speed. But chin up, fellow fighters, our time for victory may soon be near...

+
+ +
+

Is Chuck Norris a Cat Person?

+

Chuck Norris is widely regarded as the premier martial artist on the planet, and it's a complete coincidence anyone who disagrees with this fact mysteriously disappears soon after. But the real question is, is he a cat person?...

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-readability-with-high-contrast-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-readability-with-high-contrast-text.spanish.md new file mode 100644 index 0000000000..07cd930552 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/improve-readability-with-high-contrast-text.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d778e367417b2b2512aab +title: Improve Readability with High Contrast Text +localeTitle: Mejora la legibilidad con texto de alto contraste +challengeType: 0 +videoUrl: '' +--- + +## Description +
+bajo contraste entre los colores de primer plano y de fondo puede dificultar la lectura del texto. Un contraste suficiente mejora la legibilidad de su contenido, pero ¿qué significa exactamente "suficiente"? +Las Pautas de Accesibilidad al Contenido en la Web (WCAG) recomiendan al menos una relación de contraste de 4.5 a 1 para el texto normal. La relación se calcula comparando los valores de luminancia relativa de dos colores. Esto varía de 1: 1 para el mismo color, o sin contraste, a 21: 1 para blanco contra negro, el contraste más fuerte. Hay muchas herramientas de comprobación de contraste disponibles en línea que calculan esta relación para usted. +
+ +## Instructions +
+La elección del texto gris claro de Camper Cat sobre un fondo blanco para su reciente publicación en el blog tiene una relación de contraste de 1.5: 1, lo que dificulta su lectura. Cambie el color del texto del gris actual ( #D3D3D3 ) a un gris más oscuro ( #636363 ) para mejorar la relación de contraste a 6: 1. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe cambiar el color del texto del body al gris más oscuro. + testString: 'assert($("body").css("color") == "rgb(99, 99, 99)", "Your code should change the text color for the body to the darker gray.");' + - text: Su código no debe cambiar el background-color de background-color del body . + testString: 'assert($("body").css("background-color") == "rgb(255, 255, 255)", "Your code should not change the background-color for the body.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Deep Thoughts with Master Camper Cat

+
+
+

A Word on the Recent Catnip Doping Scandal

+

The influence that catnip has on feline behavior is well-documented, and its use as an herbal supplement in competitive ninja circles remains controversial. Once again, the debate to ban the substance is brought to the public's attention after the high-profile win of Kittytron, a long-time proponent and user of the green stuff, at the Claw of Fury tournament.

+

As I've stated in the past, I firmly believe a true ninja's skills must come from within, with no external influences. My own catnip use shall continue as purely recreational.

+
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/jump-straight-to-the-content-using-the-main-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/jump-straight-to-the-content-using-the-main-element.spanish.md new file mode 100644 index 0000000000..87b0afa019 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/jump-straight-to-the-content-using-the-main-element.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d774e367417b2b2512a9f +title: Jump Straight to the Content Using the main Element +localeTitle: Ir directamente al contenido usando el elemento principal +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML5 introdujo una serie de nuevos elementos que brindan a los desarrolladores más opciones al tiempo que incorporan funciones de accesibilidad. Estas etiquetas incluyen main , header , footer , nav , article y section , entre otras. +De forma predeterminada, un navegador presenta estos elementos de manera similar a la humble div . Sin embargo, usarlos cuando sea apropiado le da un significado adicional a su marca. El nombre de la etiqueta solo puede indicar el tipo de información que contiene, lo que agrega un significado semántico a ese contenido. Las tecnologías de asistencia pueden acceder a esta información para proporcionar un mejor resumen de la página o opciones de navegación para sus usuarios. +El elemento main se utiliza para envolver (usted lo adivinó) el contenido principal, y solo debe haber uno por página. Está destinado a rodear la información relacionada con el tema central de su página. No está diseñado para incluir elementos que se repiten en todas las páginas, como enlaces de navegación o banners. +La etiqueta main también tiene una característica de hito incorporada que la tecnología de asistencia puede usar para navegar rápidamente al contenido principal. Si alguna vez ha visto un enlace "Ir al contenido principal" en la parte superior de una página, el uso de una etiqueta principal otorga automáticamente esa funcionalidad a los dispositivos de asistencia. +
+ +## Instructions +
+Camper Cat tiene algunas grandes ideas para su página de armas ninja. Ayúdelo estableció su margen de beneficio mediante la adición de apertura y cierre de main etiquetas entre la header y footer (cubierto en otros desafíos). Mantener las etiquetas main vacías por ahora. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta main . + testString: 'assert($("main").length == 1, "Your code should have one main tag.");' + - text: Las etiquetas main deben estar entre la etiqueta de header cierre y la etiqueta de footer apertura. + testString: 'assert(code.match(/<\/header>\s*?
\s*?<\/main>/gi), "The main tags should be between the closing header tag and the opening footer tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +
+

Weapons of the Ninja

+
+ + + + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/know-when-alt-text-should-be-left-blank.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/know-when-alt-text-should-be-left-blank.spanish.md new file mode 100644 index 0000000000..fa78b13e61 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/know-when-alt-text-should-be-left-blank.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d774c367417b2b2512a9d +title: Know When Alt Text Should be Left Blank +localeTitle: Sepa cuándo el texto alternativo debe dejarse en blanco +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En el último desafío, aprendiste que incluir un atributo alt en las etiquetas img es obligatorio. Sin embargo, a veces las imágenes se agrupan con un título que ya las describe, o se usan solo para decoración. En estos casos, el texto alt puede parecer redundante o innecesario. +En situaciones en las que una imagen ya está explicada con contenido de texto o no agrega un significado a una página, el img aún necesita un atributo alt , pero se puede establecer en una cadena vacía. Aquí hay un ejemplo: +<img src="visualDecoration.jpeg" alt=""> +Las imágenes de fondo también suelen caer bajo la etiqueta 'decorativa'. Sin embargo, normalmente se aplican con reglas CSS y, por lo tanto, no forman parte del proceso de los lectores de pantalla de marcado. +Nota
Para imágenes con un título, es posible que desee incluir texto alt , ya que ayuda a los motores de búsqueda a catalogar el contenido de la imagen. +
+ +## Instructions +
+Camper Cat ha codificado una página de esqueleto para la parte del blog de su sitio web. Está planeando agregar un descanso visual entre sus dos artículos con una imagen decorativa de una espada samurai. Agregue un atributo alt a la etiqueta img y establézcalo en una cadena vacía. (Tenga en cuenta que la imagen src no se enlaza con un archivo real; no se preocupe si no se ven espadas en la pantalla). +
+ +## Tests +
+ +```yml +tests: + - text: Su etiqueta img debe tener un atributo alt . + testString: 'assert(!($("img").attr("alt") == undefined), "Your img tag should have an alt attribute.");' + - text: El atributo alt debe establecer en una cadena vacía. + testString: 'assert($("img").attr("alt") == "", "The alt attribute should be set to an empty string.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

Deep Thoughts with Master Camper Cat

+
+

Defeating your Foe: the Red Dot is Ours!

+

To Come...

+
+ + + +
+

Is Chuck Norris a Cat Person?

+

To Come...

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-elements-only-visible-to-a-screen-reader-by-using-custom-css.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-elements-only-visible-to-a-screen-reader-by-using-custom-css.spanish.md new file mode 100644 index 0000000000..5321fc466a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-elements-only-visible-to-a-screen-reader-by-using-custom-css.spanish.md @@ -0,0 +1,149 @@ +--- +id: 587d778d367417b2b2512aaa +title: Make Elements Only Visible to a Screen Reader by Using Custom CSS +localeTitle: Haga que los elementos solo sean visibles para un lector de pantalla utilizando CSS personalizado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+¿Ha notado que todos los desafíos de accesibilidad aplicados hasta ahora no han usado ningún CSS? Esto es para mostrar la importancia de un esquema de documento lógico y el uso de etiquetas semánticamente significativas alrededor de su contenido antes de introducir el aspecto de diseño visual. +Sin embargo, la magia de CSS también puede mejorar la accesibilidad en su página cuando desea ocultar visualmente contenido destinado solo para lectores de pantalla. Esto sucede cuando la información está en un formato visual (como un gráfico), pero los usuarios de lectores de pantalla necesitan una presentación alternativa (como una tabla) para acceder a los datos. CSS se utiliza para colocar los elementos de solo lectura de pantalla fuera del área visual de la ventana del navegador. +Aquí hay un ejemplo de las reglas CSS que logran esto: +
.sr-only {
  position: absolute;
  left: -10000px;
  width: 1px;
  height: 1px;
  top: auto;
  overflow: hidden;
}
+Nota
Los siguientes enfoques de CSS NO harán lo mismo: + +
+ +## Instructions +
+Camper Cat creó un gráfico de barras apiladas realmente genial para su página de entrenamiento y puso los datos en una tabla para sus usuarios con discapacidades visuales. La tabla ya tiene una clase sr-only , pero las reglas de CSS aún no están completas. Asigne a la position un valor absoluto, el valor left a -10000px, y el width y el height ambos valores de 1px. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la propiedad de position de la clase sr-only en un valor absoluto. + testString: 'assert($(".sr-only").css("position") == "absolute", "Your code should set the position property of the sr-only class to a value of absolute.");' + - text: Su código debe establecer la propiedad left de la clase sr-only a un valor de -10000px. + testString: 'assert($(".sr-only").css("left") == "-10000px", "Your code should set the left property of the sr-only class to a value of -10000px.");' + - text: Su código debe establecer la propiedad de width de la clase sr-only en un valor de 1 píxel. + testString: 'assert(code.match(/width:\s*?1px/gi), "Your code should set the width property of the sr-only class to a value of 1 pixel.");' + - text: Su código debe establecer la propiedad de height de la clase sr-only en un valor de 1 píxel. + testString: 'assert(code.match(/height:\s*?1px/gi), "Your code should set the height property of the sr-only class to a value of 1 pixel.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Training

+ +
+
+

Master Camper Cat's Beginner Three Week Training Program

+
+ +

[Stacked bar chart]

+
+
Breakdown per week of time to spend training in stealth, combat, and weapons.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Hours of Weekly Training in Stealth, Combat, and Weapons
Stealth & AgilityCombatWeaponsTotal
Week One35210
Week Two45312
Week Three46313
+
+
+

Stealth & Agility Training

+

Climb foliage quickly using a minimum spanning tree approach

+

No training is NP-complete without parkour

+
+
+

Combat Training

+

Dispatch multiple enemies with multithreaded tactics

+

Goodbye, world: 5 proven ways to knock out an opponent

+
+
+

Weapons Training

+

Swords: the best tool to literally divide and conquer

+

Breadth-first or depth-first in multi-weapon training?

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-links-navigatable-with-html-access-keys.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-links-navigatable-with-html-access-keys.spanish.md new file mode 100644 index 0000000000..0abbbc9573 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-links-navigatable-with-html-access-keys.spanish.md @@ -0,0 +1,82 @@ +--- +id: 587d7790367417b2b2512aaf +title: Make Links Navigatable with HTML Access Keys +localeTitle: Haga que los enlaces sean navegables con claves de acceso HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML ofrece la accesskey atributo para especificar una tecla de acceso directo para activar o traer el foco a un elemento. Esto puede hacer que la navegación sea más eficiente para usuarios que solo usan el teclado. +HTML5 permite que este atributo se use en cualquier elemento, pero es particularmente útil cuando se usa con los interactivos. Esto incluye enlaces, botones y controles de formulario. +Aquí hay un ejemplo: +<button accesskey="b">Important Button</button> +
+ +## Instructions +
+Camper Cat desea que los enlaces que se encuentran alrededor de los dos títulos de artículos de blogs tengan atajos de teclado para que los usuarios de su sitio puedan navegar rápidamente a la historia completa. Agregue un atributo de accesskey a ambos enlaces y establezca el primero en "g" (para Garfield) y el segundo en "c" (para Chuck Norris). +
+ +## Tests +
+ +```yml +tests: + - text: El código debería añadir una accesskey atributo a la a etiqueta con el id de "primera". + testString: 'assert($("#first").attr("accesskey"), "Your code should add an accesskey attribute to the a tag with the id of "first".");' + - text: El código debería añadir una accesskey atributo a la a etiqueta con el id de "segunda". + testString: 'assert($("#second").attr("accesskey"), "Your code should add an accesskey attribute to the a tag with the id of "second".");' + - text: El código debe establecer la accesskey atributo en el a etiqueta con el id de "primera" a "g". Tenga en cuenta que el caso importa. + testString: 'assert($("#first").attr("accesskey") == "g", "Your code should set the accesskey attribute on the a tag with the id of "first" to "g". Note that case matters.");' + - text: El código debe establecer la accesskey atributo en el a etiqueta con el id de "segunda" a "c". Tenga en cuenta que el caso importa. + testString: 'assert($("#second").attr("accesskey") == "c", "Your code should set the accesskey attribute on the a tag with the id of "second" to "c". Note that case matters.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Deep Thoughts with Master Camper Cat

+
+
+ + +

The Garfield Files: Lasagna as Training Fuel?

+ + +

The internet is littered with varying opinions on nutritional paradigms, from catnip paleo to hairball cleanses. But let's turn our attention to an often overlooked fitness fuel, and examine the protein-carb-NOM trifecta that is lasagna...

+
+
+ + +

Is Chuck Norris a Cat Person?

+ + +

Chuck Norris is widely regarded as the premier martial artist on the planet, and it's a complete coincidence anyone who disagrees with this fact mysteriously disappears soon after. But the real question is, is he a cat person?...

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-footer-landmark.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-footer-landmark.spanish.md new file mode 100644 index 0000000000..5583a09336 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-footer-landmark.spanish.md @@ -0,0 +1,89 @@ +--- +id: 587d7788367417b2b2512aa3 +title: Make Screen Reader Navigation Easier with the footer Landmark +localeTitle: Facilita la navegación por el lector de pantalla con el pie de página +challengeType: 0 +videoUrl: '' +--- + +## Description +
+igual que el header y la nav , el elemento de footer tiene una característica de marca incorporada que permite que los dispositivos de asistencia naveguen rápidamente hacia ella. Se utiliza principalmente para contener información de derechos de autor o enlaces a documentos relacionados que generalmente se encuentran en la parte inferior de una página. +
+ +## Instructions +
+La página de entrenamiento de Camper Cat está progresando bien. Cambie el div que usó para ajustar su información de copyright en la parte inferior de la página a un elemento de footer . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta de footer . + testString: 'assert($("footer").length == 1, "Your code should have one footer tag.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + - text: Su código debe tener una etiqueta de footer apertura y cierre. + testString: 'assert(code.match(/
+ +## Challenge Seed +
+ +
+ +```html + +
+

Training

+ +
+
+
+

Stealth & Agility Training

+

Climb foliage quickly using a minimum spanning tree approach

+

No training is NP-complete without parkour

+
+
+

Combat Training

+

Dispatch multiple enemies with multithreaded tactics

+

Goodbye world: 5 proven ways to knock out an opponent

+
+
+

Weapons Training

+

Swords: the best tool to literally divide and conquer

+

Breadth-first or depth-first in multi-weapon training?

+
+
+ + +
© 2018 Camper Cat
+ + + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-header-landmark.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-header-landmark.spanish.md new file mode 100644 index 0000000000..47c60d6de0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-header-landmark.spanish.md @@ -0,0 +1,85 @@ +--- +id: 587d7787367417b2b2512aa1 +title: Make Screen Reader Navigation Easier with the header Landmark +localeTitle: Haga que la navegación del lector de pantalla sea más fácil con el encabezado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El siguiente elemento HTML5 que agrega un significado semántico y mejora la accesibilidad es la etiqueta del header . Se usa para envolver información introductoria o enlaces de navegación para su etiqueta principal, y funciona bien con el contenido que se repite en la parte superior de varias páginas. +header +comparte la característica de hito incorporada que vio con main , permitiendo que las tecnologías de asistencia naveguen rápidamente hacia ese contenido. +Nota
header está diseñado para su uso en la etiqueta del body de su documento HTML. Esto es diferente al elemento de head , que contiene el título de la página, metainformación, etc. +
+ +## Instructions +
+Camper Cat está escribiendo algunos artículos geniales sobre el entrenamiento de ninja, y quiere agregar una página para ellos en su sitio. Cambie la div superior que actualmente contiene el h1 a una etiqueta de header . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta de header . + testString: 'assert($("header").length == 1, "Your code should have one header tag.");' + - text: Sus etiquetas de header deben envolver alrededor de la h1 . + testString: 'assert($("header").children("h1").length == 1, "Your header tags should wrap around the h1.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + - text: Asegúrese de que su elemento de header tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/header>/g) && code.match(/<\/header>/g).length === code.match(/
/g).length, "Make sure your header element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+

Training with Camper Cat

+
+ + +
+
+

Stealth & Agility Training

+

Climb foliage quickly using a minimum spanning tree approach

+

No training is NP-complete without parkour

+
+
+

Combat Training

+

Dispatch multiple enemies with multithreaded tactics

+

Goodbye world: 5 proven ways to knock out an opponent

+
+
+

Weapons Training

+

Swords: the best tool to literally divide and conquer

+

Breadth-first or depth-first in multi-weapon training?

+
+
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-nav-landmark.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-nav-landmark.spanish.md new file mode 100644 index 0000000000..7f04fdbdbc --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/make-screen-reader-navigation-easier-with-the-nav-landmark.spanish.md @@ -0,0 +1,89 @@ +--- +id: 587d7788367417b2b2512aa2 +title: Make Screen Reader Navigation Easier with the nav Landmark +localeTitle: Facilita la navegación por el lector de pantalla con el navegador Landmark +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El elemento de nav es otro elemento de HTML5 con la función de marca incorporada para facilitar la navegación del lector de pantalla. Esta etiqueta está diseñada para envolver alrededor de los enlaces de navegación principales en su página. +Si hay enlaces repetidos al sitio en la parte inferior de la página, no es necesario marcar también aquellos con una etiqueta de nav . Usar un footer (cubierto en el siguiente desafío) es suficiente. +
+ +## Instructions +
+Camper Cat incluyó enlaces de navegación en la parte superior de su página de entrenamiento, pero los envolvió en un div . Cambie el div a una etiqueta de nav para mejorar la accesibilidad en su página. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener una etiqueta de nav . + testString: 'assert($("nav").length == 1, "Your code should have one nav tag.");' + - text: Sus etiquetas de nav deben envolver alrededor de la ul y sus elementos de lista. + testString: 'assert($("nav").children("ul").length == 1, "Your nav tags should wrap around the ul and its list items.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + - text: Asegúrese de que su elemento de nav tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/nav>/g) && code.match(/<\/nav>/g).length === code.match(/
+ +## Challenge Seed +
+ +
+ +```html + +
+

Training with Camper Cat

+ +
+ +
+ +
+
+
+

Stealth & Agility Training

+

Climb foliage quickly using a minimum spanning tree approach

+

No training is NP-complete without parkour

+
+
+

Combat Training

+

Dispatch multiple enemies with multithreaded tactics

+

Goodbye world: 5 proven ways to knock out an opponent

+
+
+

Weapons Training

+

Swords: the best tool to literally divide and conquer

+

Breadth-first or depth-first in multi-weapon training?

+
+
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/standardize-times-with-the-html5-datetime-attribute.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/standardize-times-with-the-html5-datetime-attribute.spanish.md new file mode 100644 index 0000000000..caf23d2a35 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/standardize-times-with-the-html5-datetime-attribute.spanish.md @@ -0,0 +1,90 @@ +--- +id: 587d778c367417b2b2512aa9 +title: Standardize Times with the HTML5 datetime Attribute +localeTitle: Estandarizar los tiempos con el atributo datetime HTML5 +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Continuando con el tema de la fecha, HTML5 también introdujo el elemento de time junto con un atributo de datetime y datetime para estandarizar los tiempos. Este es un elemento en línea que puede ajustar una fecha u hora en una página. Un formato válido de esa fecha se mantiene en el atributo datetime . Este es el valor al que acceden los dispositivos de asistencia. Ayuda a evitar confusiones al indicar una versión estandarizada de un tiempo, incluso si está escrito de manera informal o coloquial en el texto. +Aquí hay un ejemplo: +<p>Master Camper Cat officiated the cage match between Goro and Scorpion <time datetime="2013-02-13">last Wednesday</time>, which ended in a draw.</p> +
+ +## Instructions +
+encuentran los resultados de la encuesta de Mortal Kombat de Camper Cat! Envuelva una etiqueta de time alrededor del texto "Jueves, 15 de septiembre <sup> th </sup>" y agregue un atributo de datetime y datetime establecido en "2016-09-15". +
+ +## Tests +
+ +```yml +tests: + - text: 'Sus etiquetas de time deben rodear el texto "Jueves 15 de septiembre <sup> th </sup>".' + testString: 'assert($("time").text().match(/Thursday, September 15th/g), "Your time tags should wrap around the text "Thursday, September 15<sup>th</sup>".");' + - text: Su etiqueta de time debe tener un atributo de datetime y datetime que no esté vacío. + testString: 'assert($("time").attr("datetime"), "Your time tag should have a datetime attribute that is not empty.");' + - text: Su atributo de datetime y datetime debe establecerse en un valor de 2016-09-15. + testString: 'assert($("time").attr("datetime") === "2016-09-15", "Your datetime attribute should be set to a value of 2016-09-15.");' + - text: Asegúrese de que su elemento de time tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/time>/g) && code.match(/<\/time>/g).length === 4, "Make sure your time element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Tournaments

+
+
+

Mortal Kombat Tournament Survey Results

+ + + +

Thank you to everyone for responding to Master Camper Cat's survey. The best day to host the vaunted Mortal Kombat tournament is Thursday, September 15th. May the best ninja win!

+ + + +
+

Comments:

+
+

Posted by: Sub-Zero on

+

Johnny Cage better be there, I'll finish him!

+
+
+

Posted by: Doge on

+

Wow, much combat, so mortal.

+
+
+

Posted by: The Grim Reaper on

+

Looks like I'll be busy that day.

+
+
+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-headings-to-show-hierarchical-relationships-of-content.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-headings-to-show-hierarchical-relationships-of-content.spanish.md new file mode 100644 index 0000000000..f8902d1e00 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-headings-to-show-hierarchical-relationships-of-content.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d774d367417b2b2512a9e +title: Use Headings to Show Hierarchical Relationships of Content +localeTitle: Usar encabezados para mostrar relaciones jerárquicas de contenido +challengeType: 0 +videoUrl: '' +--- + +## Description +
+encabezados (elementos h1 a h6 ) son etiquetas de trabajo que ayudan a proporcionar estructura y etiquetado a su contenido. Los lectores de pantalla pueden configurarse para leer solo los encabezados de una página, de modo que el usuario obtenga un resumen. Esto significa que es importante que las etiquetas de encabezado en su marca tengan un significado semántico y se relacionen entre sí, no para ser elegidas simplemente por sus valores de tamaño. +Significado semántico significa que la etiqueta que usa alrededor del contenido indica el tipo de información que contiene. +Si estuviera escribiendo un artículo con una introducción, un cuerpo y una conclusión, no tendría mucho sentido poner la conclusión como una subsección del cuerpo en su esquema. Debe ser su propia sección. Del mismo modo, las etiquetas de encabezado en una página web deben ir en orden e indicar las relaciones jerárquicas de su contenido. +encabezados con rango igual (o superior) inician nuevas secciones implícitas, los encabezados con subsecciones de inicio de rango inferior del anterior. +Como ejemplo, una página con un elemento h2 seguido de varias subsecciones etiquetadas con etiquetas h4 confundiría a un usuario lector de pantalla. Con seis opciones, es tentador usar una etiqueta porque se ve mejor en un navegador, pero puedes usar CSS para editar el tamaño relativo. +Un punto final, cada página debe tener siempre un elemento h1 (y solo uno), que es el tema principal de su contenido. Este y los otros encabezados son utilizados en parte por los motores de búsqueda para comprender el tema de la página. +
+ +## Instructions +
+Camper Cat quiere una página en su sitio dedicada a convertirse en ninja. Ayúdelo a arreglar los títulos para que su marca dé un significado semántico al contenido y muestre las relaciones correctas entre padres e hijos de sus secciones. Cambie todas las etiquetas h5 al nivel de título adecuado para indicar que son subsecciones de las h2 . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener seis etiquetas h3 . + testString: 'assert($("h3").length === 6, "Your code should have six h3 tags.");' + - text: Su código no debe tener ninguna etiqueta h5 . + testString: 'assert($("h5").length === 0, "Your code should not have any h5 tags.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

How to Become a Ninja

+
+

Learn the Art of Moving Stealthily

+
How to Hide in Plain Sight
+
How to Climb a Wall
+ +

Learn the Art of Battle

+
How to Strengthen your Body
+
How to Fight like a Ninja
+ +

Learn the Art of Living with Honor

+
How to Breathe Properly
+
How to Simplify your Life
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-add-keyboard-focus-to-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-add-keyboard-focus-to-an-element.spanish.md new file mode 100644 index 0000000000..209d3d57be --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-add-keyboard-focus-to-an-element.spanish.md @@ -0,0 +1,103 @@ +--- +id: 587d7790367417b2b2512ab0 +title: Use tabindex to Add Keyboard Focus to an Element +localeTitle: Use tabindex para agregar el foco de teclado a un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El atributo HTML tabindex tiene tres funciones distintas relacionadas con el enfoque del teclado de un elemento. Cuando está en una etiqueta, indica que el elemento se puede enfocar. El valor (un entero que es positivo, negativo o cero) determina el comportamiento. +Ciertos elementos, como los enlaces y los controles de formulario, reciben automáticamente el enfoque del teclado cuando un usuario se desplaza por una página. Está en el mismo orden en que los elementos vienen en el código fuente HTML. Esta misma funcionalidad se puede dar a otros elementos, como div , span p , colocando un tabindex="0" en ellos. Aquí hay un ejemplo: +<div tabindex="0">I need keyboard focus!</div> +Nota
Un valor de tabindex negativo (generalmente -1) indica que un elemento es enfocable, pero no es accesible por el teclado. Este método generalmente se usa para enfocar el contenido mediante programación (como cuando se activa un div para una ventana emergente), y está más allá del alcance de estos desafíos. +
+ +## Instructions +
+Camper Cat creó una nueva encuesta para recopilar información sobre sus usuarios. Sabe que los campos de entrada se enfocan automáticamente en el teclado, pero quiere asegurarse de que los usuarios de su teclado se detengan en las instrucciones mientras repasan los elementos. Agregue un atributo de tabindex a la etiqueta p y establezca su valor en "0". Bonus: el uso de tabindex también habilita la tabindex CSS :focus para trabajar en la etiqueta p . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar un atributo tabindex a la etiqueta p que contiene las instrucciones del formulario. + testString: 'assert($("p").attr("tabindex"), "Your code should add a tabindex attribute to the p tag that holds the form instructions.");' + - text: Su código debe establecer el atributo tabindex en la etiqueta p a un valor de 0. + testString: 'assert($("p").attr("tabindex") == "0", "Your code should set the tabindex attribute on the p tag to a value of 0.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Ninja Survey

+
+
+
+ + +

Instructions: Fill in ALL your information then click Submit

+ + + +
+
+ What level ninja are you? + +
+ +
+ + +
+
+
+ Select your favorite weapons: + +
+ +
+ +
+ + +
+
+ +

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-specify-the-order-of-keyboard-focus-for-several-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-specify-the-order-of-keyboard-focus-for-several-elements.spanish.md new file mode 100644 index 0000000000..f62c4f6bff --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/use-tabindex-to-specify-the-order-of-keyboard-focus-for-several-elements.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d7790367417b2b2512ab1 +title: Use tabindex to Specify the Order of Keyboard Focus for Several Elements +localeTitle: Use tabindex para especificar el orden de enfoque del teclado para varios elementos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El atributo tabindex también especifica el orden de tabulación exacto de los elementos. Esto se logra cuando el valor del atributo se establece en un número positivo de 1 o superior. +Establecer un tabindex = "1" traerá el foco del teclado a ese elemento primero. Luego pasa por la secuencia de valores de tabindex especificados (2, 3, etc.), antes de pasar a los elementos predeterminados y tabindex="0" . +Es importante tener en cuenta que cuando el orden de tabulación se establece de esta manera, anula el orden predeterminado (que utiliza la fuente HTML). Esto puede confundir a los usuarios que esperan comenzar la navegación desde la parte superior de la página. Esta técnica puede ser necesaria en algunas circunstancias, pero en términos de accesibilidad, tenga cuidado antes de aplicarla. +Aquí hay un ejemplo: +<div tabindex="1">I get keyboard focus, and I get it first!</div> +<div tabindex="2">I get keyboard focus, and I get it second!</div> +
+ +## Instructions +
+Camper Cat tiene un campo de búsqueda en su página de citas inspiradoras que planea posicionar en la esquina superior derecha con CSS. Quiere que la input búsqueda y input controles de formulario de input sean los dos primeros elementos en el orden de tabulación. Agregue un tabindex atributos de tabindex a "1" a la input búsqueda, y un atributo de tabindex establecido a "2" a la input envío. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar un atributo tabindex a la etiqueta de input búsqueda. + testString: 'assert($("#search").attr("tabindex"), "Your code should add a tabindex attribute to the search input tag.");' + - text: Su código debe agregar un atributo tabindex a la etiqueta de input envío. + testString: 'assert($("#submit").attr("tabindex"), "Your code should add a tabindex attribute to the submit input tag.");' + - text: Su código debe establecer el atributo tabindex en la etiqueta de input búsqueda a un valor de 1. + testString: 'assert($("#search").attr("tabindex") == "1", "Your code should set the tabindex attribute on the search input tag to a value of 1.");' + - text: Su código debe establecer el atributo tabindex en la etiqueta de input envío a un valor de 2. + testString: 'assert($("#submit").attr("tabindex") == "2", "Your code should set the tabindex attribute on the submit input tag to a value of 2.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Even Deeper Thoughts with Master Camper Cat

+ +
+
+ + + + + + + +
+

Inspirational Quotes

+
+

“There's no Theory of Evolution, just a list of creatures I've allowed to live.”
+ - Chuck Norris

+
+
+

“Wise men say forgiveness is divine, but never pay full price for late pizza.”
+ - TMNT

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-content-in-the-article-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-content-in-the-article-element.spanish.md new file mode 100644 index 0000000000..58f3188a71 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-content-in-the-article-element.spanish.md @@ -0,0 +1,78 @@ +--- +id: 587d774e367417b2b2512aa0 +title: Wrap Content in the article Element +localeTitle: Envolver contenido en el artículo Elemento. +challengeType: 0 +videoUrl: '' +--- + +## Description +
+article es otro de los nuevos elementos HTML5 que agrega un significado semántico a su marca. Article es un elemento de sección y se utiliza para envolver contenido independiente y autónomo. La etiqueta funciona bien con entradas de blog, publicaciones en foros o artículos de noticias. +Determinar si el contenido puede ser independiente por lo general es una decisión de juicio, pero hay un par de pruebas simples que puede usar. Pregúntese si eliminó todo el contexto circundante, ¿ese contenido aún tendría sentido? De manera similar, para el texto, ¿se mantendría el contenido si estuviera en una fuente RSS? +Recuerde que las personas que usan tecnologías de asistencia confían en un marcado organizado semánticamente significativo para comprender mejor su trabajo. +Nota sobre la section y div
El elemento de section también es nuevo con HTML5 y tiene un significado semántico ligeramente diferente al article . Un article es para contenido independiente, y una section es para agrupar contenido relacionado temáticamente. Se pueden usar uno dentro del otro, según sea necesario. Por ejemplo, si un libro es el article , entonces cada capítulo es una section . Cuando no haya una relación entre grupos de contenido, use un div . +
<div> - groups content
<section> - groups related content
<article> - groups independent, self-contained content
+
+ +## Instructions +
+Camper Cat usó etiquetas de article para envolver las publicaciones en su página de blog, pero se olvidó de usarlas en la parte superior. Cambie la etiqueta div para usar una etiqueta de article lugar. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe tener tres etiquetas de article . + testString: 'assert($("article").length == 3, "Your code should have three article tags.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

Deep Thoughts with Master Camper Cat

+
+
+

The Garfield Files: Lasagna as Training Fuel?

+

The internet is littered with varying opinions on nutritional paradigms, from catnip paleo to hairball cleanses. But let's turn our attention to an often overlooked fitness fuel, and examine the protein-carb-NOM trifecta that is lasagna...

+
+ + + +
+

Defeating your Foe: the Red Dot is Ours!

+

Felines the world over have been waging war on the most persistent of foes. This red nemesis combines both cunning stealth and lightening speed. But chin up, fellow fighters, our time for victory may soon be near...

+
+ + + +
+

Is Chuck Norris a Cat Person?

+

Chuck Norris is widely regarded as the premier martial artist on the planet, and it's a complete coincidence anyone who disagrees with this fact mysteriously disappears soon after. But the real question is, is he a cat person?...

+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-radio-buttons-in-a-fieldset-element-for-better-accessibility.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-radio-buttons-in-a-fieldset-element-for-better-accessibility.spanish.md new file mode 100644 index 0000000000..946534c0de --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-radio-buttons-in-a-fieldset-element-for-better-accessibility.spanish.md @@ -0,0 +1,106 @@ +--- +id: 587d778b367417b2b2512aa7 +title: Wrap Radio Buttons in a fieldset Element for Better Accessibility +localeTitle: Envuelva los botones de radio en un elemento fieldset para una mejor accesibilidad +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El siguiente tema del formulario cubre la accesibilidad de los botones de radio. A cada opción se le asigna una label con un atributo for vincula con el id del elemento correspondiente tal como se describe en el último desafío. Dado que los botones de radio a menudo vienen en un grupo donde el usuario debe elegir uno, hay una manera de mostrar semánticamente que las opciones son parte de un conjunto. +La etiqueta de fieldset rodea todo el grupo de botones de radio para lograr esto. A menudo utiliza una etiqueta de legend para proporcionar una descripción de la agrupación, que los lectores de pantalla leen para cada opción en el elemento fieldset . +El fieldset y la etiqueta de legend no son necesarios cuando las opciones son autoexplicativas, como una selección de género. Usando una label con el for atributo para cada botón de radio es suficiente. +Aquí hay un ejemplo: +
<form>
  <fieldset>
    <legend>Choose one of these three items:</legend>
    <input id="one" type="radio" name="items" value="one">
    <label for="one">Choice One</label><br>
    <input id="two" type="radio" name="items" value="two">
    <label for="two">Choice Two</label><br>
    <input id="three" type="radio" name="items" value="three">
    <label for="three">Choice Three</label>
  </fieldset>
</form>
+
+ +## Instructions +
+Camper Cat desea información sobre el nivel de ninja de sus usuarios cuando se registran en su lista de correo electrónico. Ha añadido un conjunto de botones de radio, y aprendió de la lección anterior para utilizar etiquetas de la etiqueta con la for atributos para cada elección. ¡Ve el gato campista! Sin embargo, su código todavía necesita ayuda. Cambie la etiqueta div rodea a los botones de fieldset una etiqueta de conjunto de fieldset y cambie la etiqueta p dentro de una legend . +
+ +## Tests +
+ +```yml +tests: + - text: El código debe tener un fieldset de etiqueta en todo el juego de botones circulares. + testString: 'assert($("fieldset").length == 1, "Your code should have a fieldset tag around the radio button set.");' + - text: Asegúrese de que su elemento fieldset tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/fieldset>/g) && code.match(/<\/fieldset>/g).length === code.match(/
/g).length, "Make sure your fieldset element has a closing tag.");' + - text: Tu código debe tener una etiqueta de legend alrededor del texto que pregunta qué nivel de ninja es un usuario. + testString: 'assert($("legend").length == 1, "Your code should have a legend tag around the text asking what level ninja a user is.");' + - text: Su código no debe tener ninguna etiqueta div . + testString: 'assert($("div").length == 0, "Your code should not have any div tags.");' + - text: Tu código ya no debería tener una etiqueta p alrededor del texto que pregunta qué nivel de ninja es un usuario. + testString: 'assert($("p").length == 4, "Your code should no longer have a p tag around the text asking what level ninja a user is.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Deep Thoughts with Master Camper Cat

+
+
+
+

Sign up to receive Camper Cat's blog posts by email here!

+ + + + + +
+

What level ninja are you?

+ +
+ +
+ + +
+ + + + +
+
+
+

The Garfield Files: Lasagna as Training Fuel?

+

The internet is littered with varying opinions on nutritional paradigms, from catnip paleo to hairball cleanses. But let's turn our attention to an often overlooked fitness fuel, and examine the protein-carb-NOM trifecta that is lasagna...

+
+ +
+

Defeating your Foe: the Red Dot is Ours!

+

Felines the world over have been waging war on the most persistent of foes. This red nemesis combines both cunning stealth and lightening speed. But chin up, fellow fighters, our time for victory may soon be near...

+
+ +
+

Is Chuck Norris a Cat Person?

+

Chuck Norris is widely regarded as the premier martial artist on the planet, and it's a complete coincidence anyone who disagrees with this fact mysteriously disappears soon after. But the real question is, is he a cat person?...

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/add-a-box-shadow-to-a-card-like-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/add-a-box-shadow-to-a-card-like-element.spanish.md new file mode 100644 index 0000000000..2e80c0d77c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/add-a-box-shadow-to-a-card-like-element.spanish.md @@ -0,0 +1,102 @@ +--- +id: 587d781b367417b2b2512abe +title: Add a box-shadow to a Card-like Element +localeTitle: Agregar una sombra de cuadro a un elemento similar a una tarjeta +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad box-shadow aplica una o más sombras a un elemento. +La propiedad box-shadow toma valores para offset-x (la distancia para empujar la sombra horizontalmente desde el elemento), offset-y (la distancia para empujar la sombra verticalmente desde el elemento), blur-radius , spread-radius y a Valor del color, en ese orden. Los valores de spread-radius blur-radius spread-radius son opcionales. +Aquí hay un ejemplo del CSS para crear múltiples sombras con un poco de desenfoque, en su mayoría en colores negros transparentes: +
box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
+
+ +## Instructions +
+El elemento ahora tiene un ID de thumbnail . Con este selector, use los valores de CSS de ejemplo anteriores para colocar una box-shadow en la tarjeta. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una propiedad de box-shadow para la identificación de la thumbnail . + testString: 'assert(code.match(/#thumbnail\s*?{\s*?box-shadow/g), "Your code should add a box-shadow property for the thumbnail id.");' + - text: Deberías usar el CSS dado para el valor de la box-shadow la box-shadow . + testString: 'assert(code.match(/box-shadow:\s*?0\s+?10px\s+?20px\s+?rgba\(\s*?0\s*?,\s*?0\s*?,\s*?0\s*?,\s*?0?\.19\),\s*?0\s+?6px\s+?6px\s+?rgba\(\s*?0\s*?,\s*?0\s*?,\s*?0\s*?,\s*?0?\.23\)/gi), "You should use the given CSS for the box-shadow value.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Alphabet

+
+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "#thumbnail {box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-background-color-property-of-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-background-color-property-of-text.spanish.md new file mode 100644 index 0000000000..51bbd79caf --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-background-color-property-of-text.spanish.md @@ -0,0 +1,100 @@ +--- +id: 587d781b367417b2b2512abc +title: Adjust the background-color Property of Text +localeTitle: Ajustar la propiedad de texto de color de fondo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En lugar de ajustar el fondo general o el color del texto para que el primer plano sea fácil de leer, puede agregar un background-color al elemento que contiene el texto que desea enfatizar. Este desafío utiliza rgba() lugar de códigos hex o rgb() normal. +
rgba stands for:
  r = red
  g = green
  b = blue
  a = alpha/level of opacity
+Los valores RGB pueden variar de 0 a 255. El valor alfa puede variar de 1, que es totalmente opaco o de color sólido, a 0, que es completamente transparente o claro. rgba() es excelente para usar en este caso, ya que le permite ajustar la opacidad. Esto significa que no tienes que bloquear completamente el fondo. +background-color: rgba(45, 45, 45, 0.1) para este desafío. Produce un color gris oscuro que es casi transparente dado el bajo valor de opacidad de 0.1. +
+ +## Instructions +
+Para hacer que el texto destaque más, ajuste el background-color de background-color del elemento h4 al valor rgba() dado. +También para el h4 , elimine la propiedad de height y agregue padding de 10px. +
+ +## Tests +
+ +```yml +tests: + - text: 'Su código debe agregar una propiedad de background-color al conjunto de elementos h4 en rgba(45, 45, 45, 0.1) .' + testString: 'assert(code.match(/background-color:\s*?rgba\(\s*?45\s*?,\s*?45\s*?,\s*?45\s*?,\s*?0?\.1\s*?\)/gi), "Your code should add a background-color property to the h4 element set to rgba(45, 45, 45, 0.1).");' + - text: Su código debe agregar una propiedad de padding al elemento h4 y establecerlo en 10 píxeles. + testString: 'assert($("h4").css("padding-top") == "10px" && $("h4").css("padding-right") == "10px" && $("h4").css("padding-bottom") == "10px" && $("h4").css("padding-left") == "10px", "Your code should add a padding property to the h4 element and set it to 10 pixels.");' + - text: La propiedad de height en el elemento h4 debe ser eliminada. + testString: 'assert(!($("h4").css("height") == "25px"), "The height property on the h4 element should be removed.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Alphabet

+
+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-color-of-various-elements-to-complementary-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-color-of-various-elements-to-complementary-colors.spanish.md new file mode 100644 index 0000000000..1cb5506e4c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-color-of-various-elements-to-complementary-colors.spanish.md @@ -0,0 +1,95 @@ +--- +id: 587d78a4367417b2b2512ad3 +title: Adjust the Color of Various Elements to Complementary Colors +localeTitle: Ajustar el color de varios elementos a colores complementarios +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El desafío de los colores complementarios mostró que los colores opuestos en la rueda de colores pueden hacer que cada uno se vea más vibrante cuando se colocan lado a lado. Sin embargo, el fuerte contraste visual puede ser discordante si se usa en exceso en un sitio web, y algunas veces puede hacer que el texto sea más difícil de leer si se coloca sobre un fondo de color complementario. En la práctica, uno de los colores suele ser dominante y el complemento se utiliza para atraer la atención visual a cierto contenido de la página. +
+ +## Instructions +
+Esta página utilizará un tono de verde azulado ( #09A7A1 ) como color dominante, y su complemento naranja ( #FF790E ) para resaltar visualmente los botones de #FF790E . Cambie el background-color de background-color del header y del footer de footer de negro al color verde azulado. Luego cambia el color texto h2 a teal también. Finalmente, cambie el background-color de background-color del button al color naranja. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento del header debe tener un background-color de background-color de # 09A7A1.' + testString: 'assert($("header").css("background-color") == "rgb(9, 167, 161)", "The header element should have a background-color of #09A7A1.");' + - text: 'El elemento de footer debe tener un background-color de background-color de # 09A7A1.' + testString: 'assert($("footer").css("background-color") == "rgb(9, 167, 161)", "The footer element should have a background-color of #09A7A1.");' + - text: 'El elemento h2 debe tener un color de # 09A7A1.' + testString: 'assert($("h2").css("color") == "rgb(9, 167, 161)", "The h2 element should have a color of #09A7A1.");' + - text: 'El elemento del button debe tener un background-color de background-color de # FF790E.' + testString: 'assert($("button").css("background-color") == "rgb(255, 121, 14)", "The button element should have a background-color of #FF790E.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+

Cooking with FCC!

+
+
+
+

Machine Learning in the Kitchen

+

Join this two day workshop that walks through how to implement cutting-edge snack-getting algorithms with a command line interface. Coding usually involves writing exact instructions, but sometimes you need your computer to execute flexible commands, like fetch Pringles.

+ +
+
+

Bisection Vegetable Chopping

+

This week-long retreat will level-up your coding ninja skills to actual ninja skills. No longer is the humble bisection search limited to sorted arrays or coding interview questions, applying its concepts in the kitchen will have you chopping carrots in O(log n) time before you know it.

+ +
+
+
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-height-of-an-element-using-the-height-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-height-of-an-element-using-the-height-property.spanish.md new file mode 100644 index 0000000000..452230c263 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-height-of-an-element-using-the-height-property.spanish.md @@ -0,0 +1,87 @@ +--- +id: 587d7791367417b2b2512ab5 +title: Adjust the Height of an Element Using the height Property +localeTitle: Ajustar la altura de un elemento usando la propiedad height +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede especificar la altura de un elemento utilizando la propiedad de height en CSS, similar a la propiedad de width . Aquí hay un ejemplo que cambia la altura de una imagen a 20px: +
img {
  height: 20px;
}
+
+ +## Instructions +
+Agregue una propiedad de height a la etiqueta h4 y configúrela a 25px. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe cambiar la propiedad de height h4 a un valor de 25 píxeles. + testString: 'assert($("h4").css("height") == "25px", "Your code should change the h4 height property to a value of 25 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hover-state-of-an-anchor-tag.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hover-state-of-an-anchor-tag.spanish.md new file mode 100644 index 0000000000..18801b152a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hover-state-of-an-anchor-tag.spanish.md @@ -0,0 +1,64 @@ +--- +id: 587d781d367417b2b2512ac8 +title: Adjust the Hover State of an Anchor Tag +localeTitle: Ajustar el estado de desplazamiento de una etiqueta de anclaje +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Este reto tocará el uso de pseudo-clases. Una pseudo-clase es una palabra clave que se puede agregar a los selectores para seleccionar un estado específico del elemento. +Por ejemplo, el estilo de una etiqueta de anclaje se puede cambiar para su estado de activación mediante el uso del selector de pseudo-clase :hover . Aquí está el CSS para cambiar el color de la etiqueta de anclaje a rojo durante su estado de desplazamiento: +
a:hover {
  color: red;
}
+
+ +## Instructions +
+El editor de código tiene una regla CSS para el estilo de todo a negro etiquetas. Añadir una regla de modo que cuando el usuario se desplaza sobre la a etiqueta, el color es de color azul. +
+ +## Tests +
+ +```yml +tests: + - text: 'El color etiqueta de anclaje debe permanecer en negro, solo agregue reglas CSS para el :hover estado de :hover '. + testString: 'assert($("a").css("color") == "rgb(0, 0, 0)", "The anchor tag color should remain black, only add CSS rules for the :hover state.");' + - text: La etiqueta de anclaje debe tener un color azul en el hover. + testString: 'assert(code.match(/a:hover\s*?{\s*?color:\s*?blue;\s*?}/gi), "The anchor tag should have a color of blue on hover.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +CatPhotoApp +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hue-of-a-color.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hue-of-a-color.spanish.md new file mode 100644 index 0000000000..4c8f06b684 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-hue-of-a-color.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d78a4367417b2b2512ad4 +title: Adjust the Hue of a Color +localeTitle: Ajustar el tono de un color +challengeType: 0 +videoUrl: '' +--- + +## Description +
+colores tienen varias características que incluyen matiz, saturación y luminosidad. CSS3 introdujo la propiedad hsl() como una forma alternativa de elegir un color al establecer directamente estas características. +Hue es lo que la gente generalmente considera como 'color'. Si imaginas un espectro de colores comenzando con rojo a la izquierda, moviéndote a través de verde en el medio y azul a la derecha, el tono es donde un color se ajusta a lo largo de esta línea. En hsl() , el tono utiliza un concepto de rueda de color en lugar del espectro, donde el ángulo del color en el círculo se da como un valor entre 0 y 360. +Saturación es la cantidad de gris en un color. Un color completamente saturado no tiene gris, y un color mínimamente saturado es casi completamente gris. Esto se da como un porcentaje con 100% completamente saturado. +luminosidad es la cantidad de blanco o negro en un color. Se da un porcentaje que va del 0% (negro) al 100% (blanco), donde el 50% es el color normal. +Aquí hay algunos ejemplos de hsl() usar hsl() con colores de luminosidad normal completamente saturados: +
Color HSL
rojo hsl (0, 100%, 50%)
amarillo hsl (60, 100%, 50%)
verde hsl (120, 100%, 50%)
cian hsl (180, 100%, 50%)
azul hsl (240, 100%, 50%)
magenta hsl (300, 100%, 50%)
+
+ +## Instructions +
+Cambie el background-color de background-color de cada elemento div función de los nombres de clase ( green , cyan o blue ) usando hsl() . Los tres deben tener saturación completa y luminosidad normal. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe usar la propiedad hsl() para declarar el color verde. + testString: 'assert(code.match(/\.green\s*?{\s*?background-color:\s*?hsl/gi), "Your code should use the hsl() property to declare the color green.");' + - text: Su código debe usar la propiedad hsl() para declarar el color cian. + testString: 'assert(code.match(/\.cyan\s*?{\s*?background-color:\s*?hsl/gi), "Your code should use the hsl() property to declare the color cyan.");' + - text: Su código debe usar la propiedad hsl() para declarar el color azul. + testString: 'assert(code.match(/\.blue\s*?{\s*?background-color:\s*?hsl/gi), "Your code should use the hsl() property to declare the color blue.");' + - text: El elemento div con clase green debe tener un background-color de background-color verde. + testString: 'assert($(".green").css("background-color") == "rgb(0, 255, 0)", "The div element with class green should have a background-color of green.");' + - text: El elemento div con cyan clase debe tener un background-color de background-color de cian. + testString: 'assert($(".cyan").css("background-color") == "rgb(0, 255, 255)", "The div element with class cyan should have a background-color of cyan.");' + - text: El elemento div con clase blue debe tener un background-color de background-color azul. + testString: 'assert($(".blue").css("background-color") == "rgb(0, 0, 255)", "The div element with class blue should have a background-color of blue.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-size-of-a-header-versus-a-paragraph-tag.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-size-of-a-header-versus-a-paragraph-tag.spanish.md new file mode 100644 index 0000000000..a494f5c19f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-size-of-a-header-versus-a-paragraph-tag.spanish.md @@ -0,0 +1,92 @@ +--- +id: 587d781b367417b2b2512abd +title: Adjust the Size of a Header Versus a Paragraph Tag +localeTitle: Ajustar el tamaño de un encabezado frente a una etiqueta de párrafo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El tamaño de fuente de las etiquetas de encabezado ( h1 a h6 ) generalmente debe ser mayor que el tamaño de fuente de las etiquetas de párrafo. Esto hace que sea más fácil para el usuario entender visualmente el diseño y el nivel de importancia de todo en la página. Utiliza la propiedad de font-size para ajustar el tamaño del texto en un elemento. +
+ +## Instructions +
+Para hacer que el encabezado sea significativamente más grande que el párrafo, cambie el font-size de font-size de la etiqueta h4 a 27 píxeles. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una propiedad de font-size al conjunto de elementos h4 a 27 píxeles. + testString: 'assert($("h4").css("font-size") == "27px", "Your code should add a font-size property to the h4 element set to 27 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Alphabet

+
+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-tone-of-a-color.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-tone-of-a-color.spanish.md new file mode 100644 index 0000000000..704b9e70f9 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-tone-of-a-color.spanish.md @@ -0,0 +1,94 @@ +--- +id: 587d78a4367417b2b2512ad5 +title: Adjust the Tone of a Color +localeTitle: Ajustar el tono de un color +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La opción hsl() en CSS también facilita el ajuste del tono de un color. Mezclar el blanco con un tono puro crea un tinte de ese color, y agregar negro creará un tono. Alternativamente, se produce un tono agregando gris o teñiendo y sombreando. Recuerde que la 's' y la 'l' de hsl() representan la saturación y la luminosidad, respectivamente. El porcentaje de saturación cambia la cantidad de gris y el porcentaje de luminosidad determina la cantidad de blanco o negro que hay en el color. Esto es útil cuando tienes un tono base que te gusta, pero necesitas diferentes variaciones de él. +
+ +## Instructions +
+La barra de navegación en este sitio actualmente hereda su background-color de background-color del elemento del header . Comenzando con ese color como base, agregue un background-color al elemento de nav para que use el mismo tono cian, pero tiene 80% de saturación y 25% de luminosidad para cambiar su tono y tono. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento de nav debe tener un background-color de background-color del tono cian ajustado utilizando la propiedad hsl() . + testString: 'assert(code.match(/nav\s*?{\s*?background-color:\s*?hsl\(180,\s*?80%,\s*?25%\)/gi), "The nav element should have a background-color of the adjusted cyan tone using the hsl() property.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+

Cooking with FCC!

+ +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "nav {background-color: hsl(180, 80%, 25%);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-width-of-an-element-using-the-width-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-width-of-an-element-using-the-width-property.spanish.md new file mode 100644 index 0000000000..9081e47768 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/adjust-the-width-of-an-element-using-the-width-property.spanish.md @@ -0,0 +1,88 @@ +--- +id: 587d7791367417b2b2512ab4 +title: Adjust the Width of an Element Using the width Property +localeTitle: Ajustar el ancho de un elemento usando la propiedad width +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede especificar el ancho de un elemento utilizando la propiedad width en CSS. Los valores se pueden dar en unidades de longitud relativa (como em), unidades de longitud absoluta (como px) o como un porcentaje de su elemento principal que contiene. Aquí hay un ejemplo que cambia el ancho de una imagen a 220px: +
img {
  width: 220px;
}
+
+ +## Instructions +
+Agregue una propiedad de width a toda la tarjeta y establézcala en un valor absoluto de 245px. Usa la clase fullCard para seleccionar el elemento. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe cambiar la propiedad de width de la tarjeta a 245 píxeles usando el selector de clase fullCard . + testString: 'assert(code.match(/.fullCard\s*{[\s\S][^}]*\n*^\s*width\s*:\s*245px\s*;/gm), "Your code should change the width property of the card to 245 pixels by using the fullCard class selector.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".fullCard {\nwidth: 245px; border: 1px solid #ccc; border-radius: 5px; margin: 10px 5px; padding: 4px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-at-variable-rates.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-at-variable-rates.spanish.md new file mode 100644 index 0000000000..d8a63f1f4d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-at-variable-rates.spanish.md @@ -0,0 +1,106 @@ +--- +id: 587d78a8367417b2b2512ae5 +title: Animate Elements at Variable Rates +localeTitle: Animar elementos a tasas variables +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hay una variedad de formas de alterar las tasas de animación de elementos animados similares. Hasta ahora, esto se ha logrado mediante la aplicación de una propiedad de animation-iteration-count y la configuración de reglas de @keyframes . +Para ilustrar, la animación de la derecha consta de dos "estrellas" que disminuyen de tamaño y opacidad en la marca del 20% en la regla @keyframes , que crea la animación de @keyframes . Puede cambiar la regla @keyframes para uno de los elementos para que las estrellas parpadeen a diferentes velocidades. +
+ +## Instructions +
+Modifique la tasa de animación del elemento con el nombre de clase de star-1 cambiando su regla @keyframes al 50%. +
+ +## Tests +
+ +```yml +tests: + - text: La regla @keyframes para la clase star-1 debe ser del 50%. + testString: 'assert(code.match(/twinkle-1\s*?{\s*?50%/g), "The @keyframes rule for the star-1 class should be 50%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "@keyframes twinkle-1 {50% {transform: scale(0.5); opacity: 0.5;}}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-continually-using-an-infinite-animation-count.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-continually-using-an-infinite-animation-count.spanish.md new file mode 100644 index 0000000000..d1ffefdcf2 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-elements-continually-using-an-infinite-animation-count.spanish.md @@ -0,0 +1,86 @@ +--- +id: 587d78a8367417b2b2512ae3 +title: Animate Elements Continually Using an Infinite Animation Count +localeTitle: Animar elementos continuamente utilizando un recuento de animaciones infinitas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los desafíos anteriores cubrían cómo usar algunas de las propiedades de animación y la regla @keyframes . Otra propiedad de la animation-iteration-count es la animation-iteration-count , que le permite controlar cuántas veces le gustaría recorrer la animación. Aquí hay un ejemplo: +animation-iteration-count: 3; +En este caso, la animación se detendrá después de ejecutarse 3 veces, pero es posible hacer que la animación se ejecute continuamente estableciendo ese valor en infinito. +
+ +## Instructions +
+Para mantener la bola rebotando a la derecha en un bucle continuo, cambie la propiedad de animation-iteration-count a infinito. +
+ +## Tests +
+ +```yml +tests: + - text: La propiedad animation-iteration-count debe tener un valor infinito. + testString: 'assert($("#ball").css("animation-iteration-count") == "infinite", "The animation-iteration-count property should have a value of infinite.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-multiple-elements-at-variable-rates.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-multiple-elements-at-variable-rates.spanish.md new file mode 100644 index 0000000000..86f6768e58 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/animate-multiple-elements-at-variable-rates.spanish.md @@ -0,0 +1,109 @@ +--- +id: 587d78a8367417b2b2512ae6 +title: Animate Multiple Elements at Variable Rates +localeTitle: Animar múltiples elementos a tasas variables +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En el desafío anterior, cambiaste las tasas de animación para dos elementos animados similares al modificar sus reglas @keyframes . Puede lograr el mismo objetivo manipulando la animation-duration de la animation-duration de varios elementos. +En la animación que se ejecuta en el editor de código, hay tres "estrellas" en el cielo que brillan al mismo ritmo en un bucle continuo. Para hacerlos brillar a diferentes velocidades, puede establecer la propiedad de animation-duration la animation-duration en diferentes valores para cada elemento. +
+ +## Instructions +
+Establezca la animation-duration de la animation-duration de los elementos con las clases star-1 , star-2 y star-3 en 1s, 0.9s y 1.1s, respectivamente. +
+ +## Tests +
+ +```yml +tests: + - text: La propiedad de animation-duration para la estrella con clase star-1 debe permanecer en 1s. + testString: 'assert($(".star-1").css("animation-duration") == "1s", "The animation-duration property for the star with class star-1 should remain at 1s.");' + - text: La propiedad de animation-duration para la estrella con clase star-2 debe ser 0.9s. + testString: 'assert($(".star-2").css("animation-duration") == "0.9s", "The animation-duration property for the star with class star-2 should be 0.9s.");' + - text: La propiedad de animation-duration para la estrella con clase star-3 debe ser 1.1s. + testString: 'assert($(".star-3").css("animation-duration") == "1.1s", "The animation-duration property for the star with class star-3 should be 1.1s.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/center-an-element-horizontally-using-the-margin-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/center-an-element-horizontally-using-the-margin-property.spanish.md new file mode 100644 index 0000000000..9822a1c00d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/center-an-element-horizontally-using-the-margin-property.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d78a3367417b2b2512ad0 +title: Center an Element Horizontally Using the margin Property +localeTitle: Centrar un elemento horizontalmente usando la propiedad de margen +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Otra técnica de posicionamiento es centrar un elemento de bloque horizontalmente. Una forma de hacerlo es establecer su margin en un valor de auto. +Este método también funciona para imágenes. Las imágenes son elementos en línea de forma predeterminada, pero se pueden cambiar a elementos de bloque cuando configura la propiedad de display para bloquear. +
+ +## Instructions +
+Centre el div en la página agregando una propiedad de margin con un valor de auto. +
+ +## Tests +
+ +```yml +tests: + - text: El div debe tener un margin establecido en auto. + testString: 'assert(code.match(/margin:\s*?auto;/g), "The div should have a margin set to auto.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "div {background-color: blue; height: 100px; width: 100px; margin: auto;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-an-elements-relative-position.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-an-elements-relative-position.spanish.md new file mode 100644 index 0000000000..f2754e8c98 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-an-elements-relative-position.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d781e367417b2b2512ac9 +title: Change an Element's Relative Position +localeTitle: Cambiar la posición relativa de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+CSS trata cada elemento HTML como su propia caja, lo que generalmente se conoce como el CSS Box Model . Los elementos de nivel de bloque se inician automáticamente en una nueva línea (piense en encabezados, párrafos y divs) mientras que los elementos en línea se ubican dentro del contenido que lo rodea (como imágenes o tramos). El diseño predeterminado de los elementos de esta manera se denomina normal flow de un documento, pero CSS ofrece la propiedad de posición para anularlo. +Cuando la posición de un elemento se establece en relative , le permite especificar cómo CSS debe moverlo en relación con su posición actual en el flujo normal de la página. Se empareja con las propiedades de desplazamiento de CSS de left o right , y de top o bottom . Estos dicen cuántos píxeles, porcentajes o ems para mover el elemento lejos de donde normalmente se coloca. El siguiente ejemplo aleja el párrafo 10 píxeles de la parte inferior: +
p {
  position: relative;
  bottom: 10px;
}
+Cambiar la posición de un elemento a relativa no lo elimina del flujo normal; otros elementos a su alrededor todavía se comportan como si ese elemento estuviera en su posición predeterminada. +Nota
El posicionamiento le brinda mucha flexibilidad y poder sobre el diseño visual de una página. Es bueno recordar que no importa la posición de los elementos, el marcado HTML subyacente debe estar organizado y tener sentido cuando se lee de arriba a abajo. Así es como los usuarios con discapacidades visuales (que dependen de dispositivos de asistencia como lectores de pantalla) acceden a su contenido. +
+ +## Instructions +
+Cambie la position del h2 a relative , y use un desplazamiento de CSS para alejarlo 15 píxeles de la top de donde se encuentra en el flujo normal. Observe que no hay impacto en las posiciones de los elementos h1 yp circundantes. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento h2 debe tener una propiedad de position establecida en relative . + testString: 'assert($("h2").css("position") == "relative", "The h2 element should have a position property set to relative.");' + - text: Su código debe usar un desplazamiento de CSS para colocar relativamente el h2 15px lejos de la top de donde normalmente se encuentra. + testString: 'assert($("h2").css("top") == "15px", "Your code should use a CSS offset to relatively position the h2 15px away from the top of where it normally sits.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

On Being Well-Positioned

+

Move me!

+

I still think the h2 is where it normally sits.

+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-animation-timing-with-keywords.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-animation-timing-with-keywords.spanish.md new file mode 100644 index 0000000000..7cd703a299 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-animation-timing-with-keywords.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d78a8367417b2b2512ae7 +title: Change Animation Timing with Keywords +localeTitle: Cambiar el tiempo de animación con palabras clave +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En las animaciones CSS, la propiedad animation-timing-function controla la rapidez con la que un elemento animado cambia a lo largo de la duración de la animación. Si la animación es un automóvil que se mueve del punto A al punto B en un tiempo determinado (la animation-duration su animation-duration ), la animation-timing-function la animation-timing-function dice cómo el automóvil acelera y desacelera en el transcurso del viaje. +Hay una serie de palabras clave predefinidas disponibles para las opciones populares. Por ejemplo, el valor predeterminado es la ease , que comienza lento, se acelera en el medio y luego se ralentiza nuevamente al final. Otras opciones incluyen la ease-out , que es rápida al principio y luego se ralentiza, la ease-in , que es lenta al principio, luego se acelera al final, o linear , que aplica una velocidad de animación constante en todo momento. +
+ +## Instructions +
+Para los elementos con el ID de ball1 y ball2 , añada una animation-timing-function propiedad para cada uno, y establecer #ball1 a linear , y #ball2 a ease-out . Observe la diferencia entre cómo se mueven los elementos durante la animación pero terminan juntos, ya que comparten la misma animation-duration de animation-duration de 2 segundos. +
+ +## Tests +
+ +```yml +tests: + - text: El valor de la propiedad de animation-timing-function para el elemento con el id ball1 debe ser lineal. + testString: 'assert($("#ball1").css("animation-timing-function") == "linear", "The value of the animation-timing-function property for the element with the id ball1 should be linear.");' + - text: El valor de la propiedad de animation-timing-function para el elemento con el id ball2 debe ser fácil de eliminar. + testString: 'assert($("#ball2").css("animation-timing-function") == "ease-out", "The value of the animation-timing-function property for the element with the id ball2 should be ease-out.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-the-position-of-overlapping-elements-with-the-z-index-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-the-position-of-overlapping-elements-with-the-z-index-property.spanish.md new file mode 100644 index 0000000000..063782066b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/change-the-position-of-overlapping-elements-with-the-z-index-property.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d78a3367417b2b2512acf +title: Change the Position of Overlapping Elements with the z-index Property +localeTitle: Cambie la posición de los elementos superpuestos con la propiedad z-index +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Cuando los elementos están posicionados para superponerse, el elemento que aparece más adelante en el marcado HTML aparecerá, de forma predeterminada, en la parte superior de los otros elementos. Sin embargo, la propiedad del z-index puede especificar el orden en que se apilan los elementos uno encima del otro. Debe ser un número entero (es decir, un número entero y no un decimal), y los valores más altos para la propiedad de z-index de un elemento lo mueven más arriba en la pila que aquellos con valores más bajos. +
+ +## Instructions +
+Agregue una propiedad de z-index al elemento con el nombre de la clase de first (el rectángulo rojo) y establézcalo en un valor de 2 para que cubra el otro elemento (rectángulo azul). +
+ +## Tests +
+ +```yml +tests: + - text: El elemento con clase first debe tener un valor de z-index de 2. + testString: 'assert($(".first").css("z-index") == "2", "The element with class first should have a z-index value of 2.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-gradual-css-linear-gradient.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-gradual-css-linear-gradient.spanish.md new file mode 100644 index 0000000000..9e3f75a62a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-gradual-css-linear-gradient.spanish.md @@ -0,0 +1,71 @@ +--- +id: 587d78a5367417b2b2512ad6 +title: Create a Gradual CSS Linear Gradient +localeTitle: Crear un gradiente lineal gradual de CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+aplicación de un color en elementos HTML no se limita a un tono plano. CSS proporciona la capacidad de usar transiciones de color, también conocidas como degradados, en elementos. Se accede a través de la función linear-gradient() la propiedad de background . Aquí está la sintaxis general: +background: linear-gradient(gradient_direction, color 1, color 2, color 3, ...); +El primer argumento especifica la dirección a partir de la cual comienza la transición de color: se puede establecer como un grado, donde 90 grados forman un degradado vertical y 45 grados se inclinan como una barra invertida. Los siguientes argumentos especifican el orden de los colores utilizados en el degradado. +Ejemplo: +background: linear-gradient(90deg, red, yellow, rgb(204, 204, 255)); +
+ +## Instructions +
+Use un linear-gradient() para el background del elemento div y #CCFFFF desde una dirección de 35 grados para cambiar el color de #CCFFFF a #FFCCCC . +Nota
Si bien hay otras formas de especificar un valor de color, como rgb() o hsl() , use valores hexadecimales para este desafío. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento div debe tener un background linear-gradient con la dirección y los colores especificados. + testString: 'assert(code.match(/background:\s*?linear-gradient\(35deg,\s*?(#CCFFFF|#CFF),\s*?(#FFCCCC|#FCC)\);/gi), "The div element should have a linear-gradient background with the specified direction and colors.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "
" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-graphic-using-css.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-graphic-using-css.spanish.md new file mode 100644 index 0000000000..87aed65ee1 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-graphic-using-css.spanish.md @@ -0,0 +1,79 @@ +--- +id: 587d78a6367417b2b2512add +title: Create a Graphic Using CSS +localeTitle: Crear un gráfico utilizando CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Al manipular diferentes selectores y propiedades, puedes hacer formas interesantes. Uno de los más fáciles de probar es una forma de luna creciente. Para este desafío, necesitas trabajar con la propiedad box-shadow que establece la sombra de un elemento, junto con la propiedad border-radius que controla la redondez de las esquinas del elemento. +Creará un objeto redondo y transparente con una sombra nítida que está ligeramente desplazada hacia el lado: la sombra realmente será la forma de la luna que ve. +Para crear un objeto redondo, la propiedad border-radius debe establecerse en un valor de 50%. +Puede recordar de un desafío anterior que la propiedad box-shadow toma valores para offset-x , offset-y , blur-radius , spread-radius y un valor de color en ese orden. Los valores de spread-radius blur-radius spread-radius son opcionales. +
+ +## Instructions +
+Manipule el elemento cuadrado en el editor para crear la forma de la luna. Primero, cambie el background-color a transparente, luego establezca la propiedad de border-radius en 50% para hacer la forma circular. Finalmente, cambie la propiedad box-shadow para establecer offset-x en 25px, offset-y en 10px, blur-radius en 0, spread-radius en 0 y color en azul. +
+ +## Tests +
+ +```yml +tests: + - text: El valor de la propiedad de background-color debe establecerse en transparent . + testString: 'assert(code.match(/background-color:\s*?transparent;/gi), "The value of the background-color property should be set to transparent.");' + - text: El valor de la propiedad border-radius debe establecer en 50% . + testString: 'assert(code.match(/border-radius:\s*?50%;/gi), "The value of the border-radius property should be set to 50%.");' + - text: 'El valor de la propiedad box-shadow debe establecerse en 25px para offset-x , 10px para offset-y , 0 para blur-radius de blur-radius , 0 para spread-radius de spread-radius y finalmente azul para el color.' + testString: 'assert(code.match(/box-shadow:\s*?25px\s+?10px\s+?0(px)?\s+?0(px)?\s+?blue\s*?;/gi), "The value of the box-shadow property should be set to 25px for offset-x, 10px for offset-y, 0 for blur-radius, 0 for spread-radius, and finally blue for the color.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".center {background-color: transparent; border-radius: 50%; box-shadow: 25px 10px 0px 0 blue;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-horizontal-line-using-the-hr-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-horizontal-line-using-the-hr-element.spanish.md new file mode 100644 index 0000000000..ed99a0fd1a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-horizontal-line-using-the-hr-element.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d781b367417b2b2512abb +title: Create a Horizontal Line Using the hr Element +localeTitle: Crear una línea horizontal utilizando el elemento hr +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede usar la etiqueta hr para agregar una línea horizontal a lo ancho del elemento que lo contiene. Esto se puede usar para definir un cambio en el tema o para separar visualmente grupos de contenido. +
+ +## Instructions +
+Agregue una etiqueta de hr debajo de la h4 que contiene el título de la tarjeta. +Nota
En HTML, hr es una etiqueta de cierre automático, y por lo tanto no necesita una etiqueta de cierre separada. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una etiqueta de hr a la marca. + testString: 'assert($("hr").length == 1, "Your code should add an hr tag to the markup.");' + - text: La etiqueta hr debe aparecer entre el título y el párrafo. + testString: 'assert(code.match(/<\/h4>\s*?|\s*?\/>)\s*?

/gi), "The hr tag should come between the title and the paragraph.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

GoogleAlphabet

+ +

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-more-complex-shape-using-css-and-html.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-more-complex-shape-using-css-and-html.spanish.md new file mode 100644 index 0000000000..608943d3ad --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-a-more-complex-shape-using-css-and-html.spanish.md @@ -0,0 +1,99 @@ +--- +id: 587d78a6367417b2b2512ade +title: Create a More Complex Shape Using CSS and HTML +localeTitle: Crea una forma más compleja usando CSS y HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Una de las formas más populares del mundo es la forma de corazón, y en este desafío creará una utilizando CSS puro. Pero primero, debe comprender los elementos pseudoelementos ::before y ::after . Estos pseudo-elementos se usan para agregar algo antes o después de un elemento seleccionado. En el siguiente ejemplo, un ::before pseudo-elemento se usa para agregar un rectángulo a un elemento con el heart la clase: +
.heart::before {
  content: "";
  background-color: yellow;
  border-radius: 25%;
  position: absolute;
  height: 50px;
  width: 70px;
  top: -50px;
  left: 5px;
}
+Para que los elementos de pseudo-elementos ::before y ::after funcionen correctamente, deben tener una propiedad de content definida. Esta propiedad se usa generalmente para agregar elementos como una foto o texto al elemento seleccionado. Cuando los pseudo-elementos ::before y ::after se usan para hacer formas, la propiedad de content sigue siendo necesaria, pero se establece en una cadena vacía. +En el ejemplo anterior, el elemento con la clase de heart tiene un pseudoelemento ::before del que produce un rectángulo amarillo con height y width de 50 px y 70 px, respectivamente. Este rectángulo tiene esquinas redondeadas debido a su radio de borde del 25% y está posicionado absolutamente a 5px desde la left y 50px por encima de la top del elemento. +
+ +## Instructions +
+Transforma el elemento en la pantalla a un corazón. En el heart::after selector, cambie el background-color a rosa y el border-radius del border-radius a 50%. +A continuación, apunte el elemento con el heart la clase (solo el heart ) y complete la propiedad de transform . Utilice la función rotate() con -45 grados. ( rotate() funciona de la misma manera que skewX() y skewY() hacen). +Finalmente, en el heart::before selector, establece su propiedad de content en una cadena vacía. +
+ +## Tests +
+ +```yml +tests: + - text: 'La propiedad de background-color de fondo del heart::after selector debe ser rosa.' + testString: 'assert(code.match(/\.heart::after\s*?{\s*?background-color\s*?:\s*?pink\s*?;/gi), "The background-color property of the heart::after selector should be pink.");' + - text: 'El border-radius del border-radius del heart::after selector debe ser del 50%.' + testString: 'assert(code.match(/border-radius\s*?:\s*?50%/gi).length == 2, "The border-radius of the heart::after selector should be 50%.");' + - text: La propiedad de transform para la clase de heart debe usar una función rotate() establecida en -45 grados. + testString: 'assert(code.match(/transform\s*?:\s*?rotate\(\s*?-45deg\s*?\)/gi), "The transform property for the heart class should use a rotate() function set to -45 degrees.");' + - text: 'El content del heart::before selector debe ser una cadena vacía.' + testString: 'assert(code.match(/\.heart::before\s*?{\s*?content\s*?:\s*?("|")\1\s*?;/gi), "The content of the heart::before selector should be an empty string.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".heart {transform: rotate(-45deg);} .heart::after {background-color: pink; border-radius: 50%;} .heart::before {content: \"\"; border-radius: 50%;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-movement-using-css-animation.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-movement-using-css-animation.spanish.md new file mode 100644 index 0000000000..b737b5a09b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-movement-using-css-animation.spanish.md @@ -0,0 +1,94 @@ +--- +id: 587d78a7367417b2b2512ae1 +title: Create Movement Using CSS Animation +localeTitle: Crear movimiento usando la animación CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Cuando los elementos tienen una position específica, como fixed o relative , las propiedades de desplazamiento de CSS right , left , top y bottom se pueden usar en las reglas de animación para crear movimiento. +Como se muestra en el ejemplo a continuación, puede empujar el elemento hacia abajo y luego hacia arriba configurando la propiedad top del 50% fotograma clave a 50px, pero configurándolo en 0px para el primer ( 0% ) y el último ( 100% ) fotograma clave . +
@keyframes rainbow {
  0% {
    background-color: blue;
    top: 0px;
  }
  50% {
    background-color: green;
    top: 50px;
  }
  100% {
    background-color: yellow;
    top: 0px;
  }
}
+
+ +## Instructions +
+Agrega un movimiento horizontal a la animación div . Usando la propiedad de desplazamiento a la left , agregue a la regla @keyframes para que rainbow comience en 0 píxeles al 0% , se mueva a 25 píxeles al 50% y termine a -25 píxeles al 100% . No reemplace la propiedad top en el editor: la animación debe tener un movimiento vertical y horizontal. +
+ +## Tests +
+ +```yml +tests: + - text: La regla @keyframes para 0% debe usar el desplazamiento left de 0px. + testString: 'assert(code.match(/0%\s*?{\s*?background-color:\s*?blue;\s*?top:\s*?0(px)?;\s*?left:\s*?0(px)?;\s*?}/gi), "The @keyframes rule for 0% should use the left offset of 0px.");' + - text: La regla @keyframes para el 50% debe usar el desplazamiento left de 25px. + testString: 'assert(code.match(/50%\s*?{\s*?background-color:\s*?green;\s*?top:\s*?50px;\s*?left:\s*?25px;\s*?}/gi), "The @keyframes rule for 50% should use the left offset of 25px.");' + - text: La regla @keyframes para el 100% debe usar el desplazamiento left de -25px. + testString: 'assert(code.match(/100%\s*?{\s*?background-color:\s*?yellow;\s*?top:\s*?0(px)?;\s*?left:\s*?-25px;\s*?}/gi), "The @keyframes rule for 100% should use the left offset of -25px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "@keyframes rainbow {0% {background-color: blue; top: 0px; left: 0px;} 50% {background-color: green; top: 50px; left: 25px;} 100% {background-color: yellow; top: 0px; left:-25px;}}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-texture-by-adding-a-subtle-pattern-as-a-background-image.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-texture-by-adding-a-subtle-pattern-as-a-background-image.spanish.md new file mode 100644 index 0000000000..30f46cfcdc --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-texture-by-adding-a-subtle-pattern-as-a-background-image.spanish.md @@ -0,0 +1,58 @@ +--- +id: 587d78a5367417b2b2512ad8 +title: Create Texture by Adding a Subtle Pattern as a Background Image +localeTitle: Crear textura agregando un patrón sutil como imagen de fondo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Una forma de agregar textura e interés a un fondo y hacer que se destaque más es agregar un patrón sutil. La clave es el equilibrio, ya que no desea que el fondo se destaque demasiado y quita el primer plano. La propiedad de background compatible con la función url() para enlazar a una imagen de la textura o patrón elegido. La dirección del enlace está entre comillas dentro de los paréntesis. +
+ +## Instructions +
+Usando la url de https://i.imgur.com/MJAkxbh.png , establezca el background de toda la página con el selector de body . +
+ +## Tests +
+ +```yml +tests: + - text: El elemento del body debe tener una propiedad de background establecida en una url() con el enlace dado. + testString: 'assert(code.match(/background:\s*?url\(\s*("|"|)https:\/\/i\.imgur\.com\/MJAkxbh\.png\1\s*\)/gi), "Your body element should have a background property set to a url() with the given link.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "body {background: url('https://i.imgur.com/MJAkxbh.png')}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-balance-using-the-text-align-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-balance-using-the-text-align-property.spanish.md new file mode 100644 index 0000000000..9c58a50821 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-balance-using-the-text-align-property.spanish.md @@ -0,0 +1,91 @@ +--- +id: 587d7791367417b2b2512ab3 +title: Create Visual Balance Using the text-align Property +localeTitle: Crear balance visual usando la propiedad text-align +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Esta sección del currículo se enfoca en el Diseño Visual Aplicado. El primer grupo de desafíos se basa en el diseño de la tarjeta dada para mostrar una serie de principios básicos. +texto es a menudo una gran parte del contenido web. CSS tiene varias opciones para alinearlo con la propiedad text-align . +text-align: justify; hace que todas las líneas de texto, excepto la última línea, se encuentren con los bordes izquierdo y derecho del cuadro de línea. +text-align: center; Centra el texto +text-align: right; alinea a la derecha el texto +y alinea el texto text-align: left; (el valor predeterminado) alinea a la izquierda el texto. +
+ +## Instructions +
+Alinee el texto de la etiqueta h4 , que dice "Google", al centro. Luego justifique la etiqueta de párrafo que contiene información sobre cómo se fundó Google. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe usar la propiedad text-align en la etiqueta h4 para establecerla en el centro. + testString: 'assert($("h4").css("text-align") == "center", "Your code should use the text-align property on the h4 tag to set it to center.");' + - text: Su código debe usar la propiedad text-align en la etiqueta p para configurarlo para justificar. + testString: 'assert($("p").css("text-align") == "justify", "Your code should use the text-align property on the p tag to set it to justify.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-direction-by-fading-an-element-from-left-to-right.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-direction-by-fading-an-element-from-left-to-right.spanish.md new file mode 100644 index 0000000000..0f4257ed6c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/create-visual-direction-by-fading-an-element-from-left-to-right.spanish.md @@ -0,0 +1,82 @@ +--- +id: 587d78a7367417b2b2512ae2 +title: Create Visual Direction by Fading an Element from Left to Right +localeTitle: Crear dirección visual mediante el desvanecimiento de un elemento de izquierda a derecha +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para este desafío, cambiará la opacity de un elemento animado para que se desvanezca gradualmente a medida que llega al lado derecho de la pantalla. +En la animación mostrada, el elemento redondo con el fondo degradado se mueve hacia la derecha en la marca del 50% de la animación según la regla @keyframes . +
+ +## Instructions +
+Dirija el elemento con el id de la ball y agregue la propiedad de opacity establecida en 0.1 al 50% , de modo que el elemento se desvanezca a medida que se mueve hacia la derecha. +
+ +## Tests +
+ +```yml +tests: + - text: La regla de keyframes para el desvanecimiento debe establecer la propiedad de opacity en 0.1 al 50%. + testString: 'assert(code.match(/@keyframes fade\s*?{\s*?50%\s*?{\s*?(?:left:\s*?60%;\s*?opacity:\s*?0?\.1;|opacity:\s*?0?\.1;\s*?left:\s*?60%;)/gi), "The keyframes rule for fade should set the opacity property to 0.1 at 50%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "@keyframes fade {50% { left: 60%; opacity: 0.1;}}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/decrease-the-opacity-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/decrease-the-opacity-of-an-element.spanish.md new file mode 100644 index 0000000000..ec7f0ef9d8 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/decrease-the-opacity-of-an-element.spanish.md @@ -0,0 +1,98 @@ +--- +id: 587d781c367417b2b2512abf +title: Decrease the Opacity of an Element +localeTitle: Disminuir la opacidad de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de opacity en CSS se usa para ajustar la opacidad o, a la inversa, la transparencia de un elemento. +
A value of 1 is opaque, which isn't transparent at all.
A value of 0.5 is half see-through.
A value of 0 is completely transparent.
+El valor dado se aplicará a todo el elemento, ya sea una imagen con alguna transparencia, o los colores de primer plano y de fondo para un bloque de texto. +
+ +## Instructions +
+Establezca la opacity de las etiquetas de anclaje en 0.7 utilizando la clase de links para seleccionarlas. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la propiedad de opacity a 0.7 en las etiquetas de anclaje seleccionando la clase de links . + testString: 'assert.approximately(parseFloat($(".links").css("opacity")), 0.7, 0.1, "Your code should set the opacity property to 0.7 on the anchor tags by selecting the class of links.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Alphabet

+
+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-complementary-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-complementary-colors.spanish.md new file mode 100644 index 0000000000..524aef557a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-complementary-colors.spanish.md @@ -0,0 +1,77 @@ +--- +id: 587d78a3367417b2b2512ad1 +title: Learn about Complementary Colors +localeTitle: Aprende sobre colores complementarios +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La teoría del color y su impacto en el diseño es un tema profundo y solo se cubren los aspectos básicos en los siguientes desafíos. En un sitio web, el color puede llamar la atención sobre el contenido, evocar emociones o crear armonía visual. El uso de diferentes combinaciones de colores puede realmente cambiar el aspecto de un sitio web, y se puede pensar mucho en elegir una paleta de colores que funcione con su contenido. +La rueda de colores es una herramienta útil para visualizar cómo se relacionan los colores entre sí: es un círculo donde los tonos similares son vecinos y los diferentes tonos están más separados. Cuando dos colores están opuestos entre sí en la rueda, se denominan colores complementarios. Tienen la característica de que si se combinan, se "cancelan" entre sí y crean un color gris. Sin embargo, cuando se colocan lado a lado, estos colores aparecen más vibrantes y producen un fuerte contraste visual. +Algunos ejemplos de colores complementarios con sus códigos hexadecimales son: +
red (#FF0000) and cyan (#00FFFF)
green (#00FF00) and magenta (#FF00FF)
blue (#0000FF) and yellow (#FFFF00)
+Esto es diferente del modelo de color RYB obsoleto que muchos de nosotros aprendimos en la escuela, que tiene diferentes colores primarios y complementarios. La teoría moderna del color utiliza el modelo RGB aditivo (como en una pantalla de computadora) y el modelo sustractivo CMY (K) (como en la impresión). Lea aquí para más información sobre este tema complejo. +Hay muchas herramientas de selección de colores disponibles en línea que tienen la opción de encontrar el complemento de un color. +Nota
Para todos los desafíos de color: usar color puede ser una forma poderosa de agregar interés visual a una página. Sin embargo, el color solo no debe usarse como la única forma de transmitir información importante porque los usuarios con discapacidades visuales pueden no entender ese contenido. Este problema se tratará con más detalle en los desafíos de accesibilidad aplicada. +
+ +## Instructions +
+Cambie la propiedad de background-color de las clases blue y yellow a sus respectivos colores. Observe cómo los colores se ven diferentes uno al lado del otro en comparación con el fondo blanco. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento div con clase blue debe tener un background-color de background-color azul. + testString: 'assert($(".blue").css("background-color") == "rgb(0, 0, 255)", "The div element with class blue should have a background-color of blue.");' + - text: El elemento div con yellow clase debe tener un background-color de background-color amarillo. + testString: 'assert($(".yellow").css("background-color") == "rgb(255, 255, 0)", "The div element with class yellow should have a background-color of yellow.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-tertiary-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-tertiary-colors.spanish.md new file mode 100644 index 0000000000..b8e5095dfe --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-about-tertiary-colors.spanish.md @@ -0,0 +1,86 @@ +--- +id: 587d78a4367417b2b2512ad2 +title: Learn about Tertiary Colors +localeTitle: Aprende sobre los colores terciarios +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los monitores de computadora y las pantallas de dispositivos crean diferentes colores al combinar cantidades de luz roja, verde y azul. Esto se conoce como el modelo de color aditivo RGB en la teoría moderna del color. Rojo (R), verde (G) y azul (B) se denominan colores primarios. La mezcla de dos colores primarios crea los colores secundarios cian (G + B), magenta (R + B) y amarillo (R + G). Viste estos colores en el desafío de los colores complementarios. Estos colores secundarios resultan ser el complemento del color primario no utilizado en su creación, y son opuestos a ese color primario en la rueda de color. Por ejemplo, el magenta está hecho con rojo y azul, y es el complemento del verde. +Los colores terciarios son el resultado de combinar un color primario con uno de sus vecinos de color secundario. Por ejemplo, el rojo (primario) y el amarillo (secundario) hacen naranja. Esto agrega seis colores más a una rueda de color simple para un total de doce. +Existen varios métodos para seleccionar diferentes colores que dan como resultado una combinación armoniosa en el diseño. Un ejemplo que puede usar colores terciarios se denomina esquema de color de división complementaria. Este esquema comienza con un color base, luego lo combina con los dos colores adyacentes a su complemento. Los tres colores proporcionan un fuerte contraste visual en un diseño, pero son más sutiles que el uso de dos colores complementarios. +Aquí hay tres colores creados usando el esquema de complemento dividido: +
Color Código hexadecimal
naranja # FF7D00
cian # 00FFFF
frambuesa # FF007D
+
+ +## Instructions +
+Cambie la propiedad de background-color de las clases de orange , cyan y raspberry a sus respectivos colores. Asegúrese de utilizar los códigos hexadecimales, ya que la naranja y la frambuesa no son nombres de colores reconocidos por el navegador. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento div con orange clase debe tener un background-color de background-color de naranja. + testString: 'assert($(".orange").css("background-color") == "rgb(255, 125, 0)", "The div element with class orange should have a background-color of orange.");' + - text: El elemento div con cyan clase debe tener un background-color de background-color de cian. + testString: 'assert($(".cyan").css("background-color") == "rgb(0, 255, 255)", "The div element with class cyan should have a background-color of cyan.");' + - text: El elemento div con raspberry clase debe tener un background-color de background-color de frambuesa. + testString: 'assert($(".raspberry").css("background-color") == "rgb(255, 0, 125)", "The div element with class raspberry should have a background-color of raspberry.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-bezier-curves-work.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-bezier-curves-work.spanish.md new file mode 100644 index 0000000000..40aa145a8b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-bezier-curves-work.spanish.md @@ -0,0 +1,96 @@ +--- +id: 587d78a9367417b2b2512ae8 +title: Learn How Bezier Curves Work +localeTitle: Aprende cómo funcionan las curvas Bezier +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El último desafío presentó la propiedad de la animation-timing-function y algunas palabras clave que cambian la velocidad de una animación a lo largo de su duración. CSS ofrece una opción distinta de las palabras clave que proporciona un control aún más preciso sobre cómo se desarrolla la animación, mediante el uso de curvas de Bezier. +En las animaciones CSS, las curvas Bezier se utilizan con la función cubic-bezier . La forma de la curva representa cómo se desarrolla la animación. La curva vive en un sistema de coordenadas 1 por 1. El eje X de este sistema de coordenadas es la duración de la animación (piense en ello como una escala de tiempo), y el eje Y es el cambio en la animación. +La función cubic-bezier consta de cuatro puntos principales que se ubican en esta cuadrícula 1 por 1: p0 , p1 , p2 y p3 . p0 y p3 están configurados para usted: son los puntos de inicio y final que siempre están ubicados respectivamente en el origen (0, 0) y (1, 1). Establece los valores de x e y para los otros dos puntos, y donde los coloque en la cuadrícula dicta la forma de la curva para que siga la animación. Esto se hace en CSS declarando los valores x e y de los puntos de "anclaje" p1 y p2 en la forma: (x1, y1, x2, y2) . Reuniéndolo todo, aquí hay un ejemplo de una curva Bezier en el código CSS: +animation-timing-function: cubic-bezier(0.25, 0.25, 0.75, 0.75); +En el ejemplo anterior, los valores x e y son equivalentes para cada punto (x1 = 0.25 = y1 y x2 = 0.2 = y2), que si recuerda de la clase de geometría, da como resultado una línea que se extiende desde el origen hasta el punto ( 1, 1). Esta animación es un cambio lineal de un elemento durante la duración de una animación, y es lo mismo que usar la palabra clave linear . En otras palabras, cambia a una velocidad constante. +
+ +## Instructions +
+Para el elemento con el id de ball1 , cambie el valor de la propiedad de animation-timing-function de linear a su valor equivalente cubic-bezier función cubic-bezier . Utilice los valores de puntos dados en el ejemplo anterior. +
+ +## Tests +
+ +```yml +tests: + - text: El valor de la propiedad de animation-timing-function para el elemento con id ball1 debería ser la función lineal-equivalente de cubic-bezier. + testString: 'assert($("#ball1").css("animation-timing-function") == "cubic-bezier(0.25, 0.25, 0.75, 0.75)", "The value of the animation-timing-function property for the element with the id ball1 should be the linear-equivalent cubic-bezier function.");' + - text: El valor de la propiedad de animation-timing-function para el elemento con el id ball2 no debe cambiar. + testString: 'assert($("#ball2").css("animation-timing-function") == "ease-out", "The value of the animation-timing-function property for the element with the id ball2 should not change.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-the-css-keyframes-and-animation-properties-work.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-the-css-keyframes-and-animation-properties-work.spanish.md new file mode 100644 index 0000000000..3be30747ed --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/learn-how-the-css-keyframes-and-animation-properties-work.spanish.md @@ -0,0 +1,85 @@ +--- +id: 587d78a7367417b2b2512adf +title: Learn How the CSS @keyframes and animation Properties Work +localeTitle: Aprende cómo funcionan las propiedades de @fotografías y animaciones de CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para animar un elemento, debe conocer las propiedades de la animación y la regla @keyframes . Las propiedades de la animación controlan el comportamiento de la animación y la regla @keyframes controla lo que sucede durante esa animación. Hay ocho propiedades de animación en total. Este desafío lo mantendrá simple y cubrirá primero los dos más importantes: +animation-name establece el nombre de la animación, que luego es utilizada por @keyframes para indicar a CSS qué reglas van con qué animaciones. +animation-duration establece el período de tiempo para la animación. +@keyframes es cómo especificar exactamente qué sucede dentro de la animación a lo largo de la duración. Esto se hace dando propiedades CSS para "marcos" específicos durante la animación, con porcentajes que van desde 0% a 100%. Si comparas esto con una película, las propiedades de CSS para 0% es cómo se muestra el elemento en la escena inicial. Las propiedades de CSS para el 100% es cómo aparece el elemento al final, justo antes de que salgan los créditos. Luego, CSS aplica la magia para hacer la transición del elemento a lo largo de la duración dada para representar la escena. Aquí hay un ejemplo para ilustrar el uso de @keyframes y las propiedades de la animación: +
#anim {
  animation-name: colorful;
  animation-duration: 3s;
}
@keyframes colorful {
  0% {
    background-color: blue;
  }
  100% {
    background-color: yellow;
  }
}
+Para el elemento con el anim ID, el fragmento de código anterior establece la animation-name de colorful y establece la animation-duration de 3 segundos. Luego, la regla @keyframes enlaza con las propiedades de animación con el nombre colorful . Establece el color azul al principio de la animación (0%), que pasará a amarillo al final de la animación (100%). No está limitado solo a las transiciones de principio a fin, puede establecer propiedades para el elemento para cualquier porcentaje entre 0% y 100%. +
+ +## Instructions +
+Cree una animación para el elemento con el id rect , estableciendo el animation-name la animation-name en arco iris y la animation-duration la animation-duration en 4 segundos. A continuación, declare una regla de @keyframes y establezca el background-color al principio de la animación ( 0% ) en azul, la mitad de la animación ( 50% ) en verde y el final de la animación ( 100% ) en amarillo. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento con id de rect debe tener una propiedad de animation-name con un valor de arco iris. + testString: 'assert($("#rect").css("animation-name") == "rainbow", "The element with id of rect should have an animation-name property with a value of rainbow.");' + - text: El elemento con id de rect debe tener una propiedad de animation-duration con un valor de 4s. + testString: 'assert($("#rect").css("animation-duration") == "4s", "The element with id of rect should have an animation-duration property with a value of 4s.");' + - text: La regla @keyframes debe usar el animation-name de animation-name de rainbow. + testString: 'assert(code.match(/@keyframes\s+?rainbow\s*?{/g), "The @keyframes rule should use the animation-name of rainbow.");' + - text: La regla @keyframes para rainbow debe usar un background-color de background-color azul al 0%. + testString: 'assert(code.match(/0%\s*?{\s*?background-color:\s*?blue;\s*?}/gi), "The @keyframes rule for rainbow should use a background-color of blue at 0%.");' + - text: La regla @keyframes para el arco iris debe usar un background-color de background-color verde al 50%. + testString: 'assert(code.match(/50%\s*?{\s*?background-color:\s*?green;\s*?}/gi), "The @keyframes rule for rainbow should use a background-color of green at 50%.");' + - text: La regla @keyframes para el arco iris debe usar un background-color de background-color amarillo al 100%. + testString: 'assert(code.match(/100%\s*?{\s*?background-color:\s*?yellow;\s*?}/gi), "The @keyframes rule for rainbow should use a background-color of yellow at 100%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-its-parent-with-absolute-positioning.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-its-parent-with-absolute-positioning.spanish.md new file mode 100644 index 0000000000..65a1dc473b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-its-parent-with-absolute-positioning.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d781e367417b2b2512acb +title: Lock an Element to its Parent with Absolute Positioning +localeTitle: Bloquear un elemento a su padre con posicionamiento absoluto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La siguiente opción para la propiedad de position CSS es absolute , que bloquea el elemento en su lugar en relación con su contenedor principal. A diferencia de la posición relative , esto elimina el elemento del flujo normal del documento, por lo que los elementos circundantes lo ignoran. Las propiedades de desplazamiento de CSS (superior o inferior e izquierda o derecha) se utilizan para ajustar la posición. +Un matiz con posicionamiento absoluto es que se bloqueará en relación con su antepasado posicionado más cercano. Si olvida agregar una regla de posición al elemento principal, (esto generalmente se hace usando position: relative; ), el navegador seguirá buscando la cadena y, por último, usará la etiqueta del cuerpo de forma predeterminada. +
+ +## Instructions +
+Bloquee el elemento #searchbar en la parte superior derecha de su section principal declarando su position como absolute . Dale las compensaciones top y right de 50 píxeles cada una. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #searchbar debería tener una position establecida en absolute .' + testString: 'assert($("#searchbar").css("position") == "absolute", "The #searchbar element should have a position set to absolute.");' + - text: 'Su código debe usar el desplazamiento de CSS top de 50 píxeles en el elemento #searchbar '. + testString: 'assert($("#searchbar").css("top") == "50px", "Your code should use the top CSS offset of 50 pixels on the #searchbar element.");' + - text: 'Su código debe usar el desplazamiento de CSS right de 50 píxeles en el elemento #searchbar '. + testString: 'assert($("#searchbar").css("right") == "50px", "Your code should use the right CSS offset of 50 pixels on the #searchbar element.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

Welcome!

+
+ +
+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-the-browser-window-with-fixed-positioning.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-the-browser-window-with-fixed-positioning.spanish.md new file mode 100644 index 0000000000..50f660f05f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/lock-an-element-to-the-browser-window-with-fixed-positioning.spanish.md @@ -0,0 +1,88 @@ +--- +id: 587d781e367417b2b2512acc +title: Lock an Element to the Browser Window with Fixed Positioning +localeTitle: Bloquee un elemento en la ventana del navegador con posicionamiento fijo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El siguiente esquema de diseño que ofrece CSS es la posición fixed , que es un tipo de posicionamiento absoluto que bloquea un elemento relativo a la ventana del navegador. Similar al posicionamiento absoluto, se usa con las propiedades de desplazamiento de CSS y también elimina el elemento del flujo normal del documento. Otros elementos ya no se "dan cuenta" de dónde se coloca, lo que puede requerir algunos ajustes de diseño en otros lugares. +Una diferencia clave entre las posiciones fixed y absolute es que un elemento con una posición fija no se moverá cuando el usuario se desplace. +
+ +## Instructions +
+La barra de navegación en el código está etiquetada con un ID de navbar de navbar . Cambie su position a fixed , y desplace 0 píxeles desde la top y 0 píxeles desde la left . Observe el (falta de) impacto en la posición h1 , no se ha empujado hacia abajo para acomodar la barra de navegación y debería ajustarse por separado. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #navbar debería tener una position establecida como fixed .' + testString: 'assert($("#navbar").css("position") == "fixed", "The #navbar element should have a position set to fixed.");' + - text: 'Su código debe usar el desplazamiento de CSS top de 0 píxeles en el elemento #navbar '. + testString: 'assert($("#navbar").css("top") == "0px", "Your code should use the top CSS offset of 0 pixels on the #navbar element.");' + - text: 'Tu código debe usar el desplazamiento de CSS left de 0 píxeles en el elemento #navbar '. + testString: 'assert($("#navbar").css("left") == "0px", "Your code should use the left CSS offset of 0 pixels on the #navbar element.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+

Welcome!

+ +
+

I shift up when the #navbar is fixed to the browser window.

+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-a-css-heartbeat-using-an-infinite-animation-count.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-a-css-heartbeat-using-an-infinite-animation-count.spanish.md new file mode 100644 index 0000000000..1209f3c3dc --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-a-css-heartbeat-using-an-infinite-animation-count.spanish.md @@ -0,0 +1,123 @@ +--- +id: 587d78a8367417b2b2512ae4 +title: Make a CSS Heartbeat using an Infinite Animation Count +localeTitle: Haz un Heartbeat CSS usando un conteo de animaciones infinitas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Aquí hay otro ejemplo de animación continua con la propiedad de animation-iteration-count que usa el corazón que diseñó en un desafío anterior. +La animación de un segundo de latido del corazón consta de dos piezas animadas. Los elementos del heart (que incluyen :before y :after piezas) se animan para cambiar el tamaño con la propiedad de transform , y la div fondo se anima para cambiar su color con la propiedad de background . +
+ +## Instructions +
+Mantenga el corazón latiendo agregando la propiedad de animation-iteration-count para la clase de back y la clase de heart y estableciendo el valor en infinito. El heart:before y heart:after selectores heart:after no necesitan propiedades de animación. +
+ +## Tests +
+ +```yml +tests: + - text: La propiedad de animation-iteration-count para la clase de heart debe tener un valor infinito. + testString: 'assert($(".heart").css("animation-iteration-count") == "infinite", "The animation-iteration-count property for the heart class should have a value of infinite.");' + - text: La propiedad animation-iteration-count para la clase back debe tener un valor infinito. + testString: 'assert($(".back").css("animation-iteration-count") == "infinite", "The animation-iteration-count property for the back class should have a value of infinite.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-motion-more-natural-using-a-bezier-curve.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-motion-more-natural-using-a-bezier-curve.spanish.md new file mode 100644 index 0000000000..e154cbe1b4 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/make-motion-more-natural-using-a-bezier-curve.spanish.md @@ -0,0 +1,91 @@ +--- +id: 587d78a9367417b2b2512aea +title: Make Motion More Natural Using a Bezier Curve +localeTitle: Haz el movimiento más natural usando una curva Bezier +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Este desafío anima un elemento para replicar el movimiento de una bola que se hace malabarismo. Los desafíos anteriores cubrieron las curvas Bezier cúbicas linear y de ease-out desahogo, sin embargo, ninguno de ellos describe con precisión el movimiento de los malabares. Necesitas personalizar una curva Bezier para esto. +La animation-timing-function automáticamente en cada fotograma clave cuando el animation-iteration-count se establece en infinito. Dado que hay una regla de fotogramas clave establecida en la mitad de la duración de la animación (al 50% ), produce dos progresiones de animación idénticas en el movimiento ascendente y descendente de la bola. +La siguiente curva de Bezier cúbica simula un movimiento de malabarismo: +cubic-bezier(0.3, 0.4, 0.5, 1.6); +Observe que el valor de y2 es mayor que 1. Aunque la curva de Bézier cúbica se asigna en un sistema de coordenadas 1 por 1, y solo puede aceptar valores de x de 1 a 1, el valor de y se puede configurar en números mayores que uno . Esto resulta en un movimiento de rebote que es ideal para simular la bola de malabarismo. +
+ +## Instructions +
+Cambie el valor de la animation-timing-function de animation-timing-function del elemento con el id de green a una función cubic-bezier con x1, y1, x2, y2 valores establecidos respectivamente en 0.311, 0.441, 0.444, 1.649. +
+ +## Tests +
+ +```yml +tests: + - text: 'El valor de la propiedad animation-timing-function para el elemento con el id green debe ser una función de cubic-bezier con los valores de x1, y1, x2, y2 según lo especificado.' + testString: 'assert($("#green").css("animation-timing-function") == "cubic-bezier(0.311, 0.441, 0.444, 1.649)", "The value of the animation-timing-function property for the element with the id green should be a cubic-bezier function with x1, y1, x2, y2 values as specified.' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/modify-fill-mode-of-an-animation.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/modify-fill-mode-of-an-animation.spanish.md new file mode 100644 index 0000000000..2be9e73b3f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/modify-fill-mode-of-an-animation.spanish.md @@ -0,0 +1,76 @@ +--- +id: 58a7a6ebf9a6318348e2d5aa +title: Modify Fill Mode of an Animation +localeTitle: Modificar el modo de relleno de una animación +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Eso es genial, pero no funciona bien todavía. Observe cómo se restablece la animación después de que hayan transcurrido 500ms , lo que hace que el botón vuelva al color original. Desea que el botón quede resaltado. +Esto se puede hacer configurando la propiedad de animation-fill-mode en forwards . La animation-fill-mode especifica el estilo aplicado a un elemento cuando la animación ha finalizado. Puedes configurarlo así: +animation-fill-mode: forwards; +
+ +## Instructions +
+Establezca la propiedad de animation-fill-mode del button:hover hacia forwards para que el botón permanezca resaltado cuando un usuario se desplace sobre él. +
+ +## Tests +
+ +```yml +tests: + - text: ' button:hover debería tener una propiedad de animation-fill-mode con un valor de forwards .' + testString: 'assert(code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-fill-mode\s*?:\s*?forwards\s*?;[\s\S]*}/gi) && code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-name\s*?:\s*?background-color\s*?;[\s\S]*}/gi) && code.match(/button\s*?:\s*?hover\s*?{[\s\S]*animation-duration\s*?:\s*?500ms\s*?;[\s\S]*}/gi), "button:hover should have a animation-fill-mode property with a value of forwards.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "button:hover {animation-name: background-color; animation-duration: 500ms; animation-fill-mode: forwards;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/move-a-relatively-positioned-element-with-css-offsets.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/move-a-relatively-positioned-element-with-css-offsets.spanish.md new file mode 100644 index 0000000000..ab8261c433 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/move-a-relatively-positioned-element-with-css-offsets.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d781e367417b2b2512aca +title: Move a Relatively Positioned Element with CSS Offsets +localeTitle: Mueva un elemento de posición relativa con compensaciones de CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las compensaciones de CSS de la top o bottom , y de la left o la right indican al navegador la distancia a la que se debe desplazar un elemento en relación con el lugar donde se ubicaría en el flujo normal del documento. Está desplazando un elemento lejos de un punto dado, lo que lo aleja del lado al que se hace referencia (efectivamente, en la dirección opuesta). Como viste en el último desafío, usando el desplazamiento superior movió el h2 hacia abajo. Del mismo modo, utilizando un desplazamiento a la izquierda mueve un elemento a la derecha. 0 + +## Instructions +
+Use las compensaciones de CSS para mover el h2 15 píxeles a la derecha y 10 píxeles hacia arriba. +
+ +## Tests +
+ +```yml +tests: + - text: 'Su código debe usar un desplazamiento de CSS para posicionar relativamente el h2 10px hacia arriba. En otras palabras, aléjelo 10px de la bottom de donde normalmente se sienta. ' + testString: 'assert($("h2").css("bottom") == "10px", "Your code should use a CSS offset to relatively position the h2 10px upwards. In other words, move it 10px away from the bottom of where it normally sits.");' + - text: 'Su código debe usar un desplazamiento de CSS para posicionar relativamente el h2 15px hacia la derecha. En otras palabras, aléjelo a 15px de la left de donde normalmente se encuentra. + testString: 'assert($("h2").css("left") == "15px", "Your code should use a CSS offset to relatively position the h2 15px towards the right. In other words, move it 15px away from the left of where it normally sits.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +

On Being Well-Positioned

+

Move me!

+

I still think the h2 is where it normally sits.

+ +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/push-elements-left-or-right-with-the-float-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/push-elements-left-or-right-with-the-float-property.spanish.md new file mode 100644 index 0000000000..0634f17a6a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/push-elements-left-or-right-with-the-float-property.spanish.md @@ -0,0 +1,82 @@ +--- +id: 587d78a3367417b2b2512ace +title: Push Elements Left or Right with the float Property +localeTitle: Empuje los elementos hacia la izquierda o hacia la derecha con la propiedad float +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La siguiente herramienta de posicionamiento no usa realmente la position , pero establece la propiedad de float de un elemento. Los elementos flotantes se eliminan del flujo normal de un documento y se empujan hacia la left o hacia la right de su elemento principal que contiene. Se usa comúnmente con la propiedad de width para especificar cuánto espacio horizontal requiere el elemento flotante. +
+ +## Instructions +
+El marcado dado funcionaría bien como un diseño de dos columnas, con la section y los elementos a aside lado uno del otro. Dé al elemento #left un float de la left y el elemento #right un float de la right . +
+ +## Tests +
+ +```yml +tests: + - text: El elemento con id left debe tener un valor float de left . + testString: 'assert($("#left").css("float") == "left", "The element with id left should have a float value of left.");' + - text: El elemento con id right debería tener un valor float de right . + testString: 'assert($("#right").css("float") == "right", "The element with id right should have a float value of right.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + + +
+

Welcome!

+
+
+

Content

+

Good stuff

+
+ + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-for-multiple-heading-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-for-multiple-heading-elements.spanish.md new file mode 100644 index 0000000000..9ae532ac5e --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-for-multiple-heading-elements.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d781c367417b2b2512ac2 +title: Set the font-size for Multiple Heading Elements +localeTitle: Establecer el tamaño de fuente para varios elementos de encabezado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de font-size se usa para especificar el tamaño del texto en un elemento dado. Esta regla se puede usar para múltiples elementos para crear una consistencia visual del texto en una página. En este desafío, establecerá los valores de todas las etiquetas h1 a h6 para equilibrar los tamaños de los títulos. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la propiedad de font-size para la etiqueta h1 en 68 píxeles. + testString: 'assert($("h1").css("font-size") == "68px", "Your code should set the font-size property for the h1 tag to 68 pixels.");' + - text: Su código debe establecer la propiedad de font-size para la etiqueta h2 a 52 píxeles. + testString: 'assert($("h2").css("font-size") == "52px", "Your code should set the font-size property for the h2 tag to 52 pixels.");' + - text: Su código debe establecer la propiedad de font-size para la etiqueta h3 en 40 píxeles. + testString: 'assert($("h3").css("font-size") == "40px", "Your code should set the font-size property for the h3 tag to 40 pixels.");' + - text: Su código debe establecer la propiedad de font-size para la etiqueta h4 a 32 píxeles. + testString: 'assert($("h4").css("font-size") == "32px", "Your code should set the font-size property for the h4 tag to 32 pixels.");' + - text: Su código debe establecer la propiedad de font-size para la etiqueta h5 en 21 píxeles. + testString: 'assert($("h5").css("font-size") == "21px", "Your code should set the font-size property for the h5 tag to 21 pixels.");' + - text: Su código debe establecer la propiedad de font-size para la etiqueta h6 en 14 píxeles. + testString: 'assert($("h6").css("font-size") == "14px", "Your code should set the font-size property for the h6 tag to 14 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

This is h1 text

+

This is h2 text

+

This is h3 text

+

This is h4 text

+
This is h5 text
+
This is h6 text
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-of-paragraph-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-of-paragraph-text.spanish.md new file mode 100644 index 0000000000..e231638d85 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-size-of-paragraph-text.spanish.md @@ -0,0 +1,59 @@ +--- +id: 587d781c367417b2b2512ac4 +title: Set the font-size of Paragraph Text +localeTitle: Establecer el tamaño de fuente del texto de párrafo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de font-size en CSS no se limita a los encabezados, se puede aplicar a cualquier elemento que contenga texto. +
+ +## Instructions +
+Cambie el valor de la propiedad de font-size para el párrafo a 16px para hacerlo más visible. +
+ +## Tests +
+ +```yml +tests: + - text: Su etiqueta p debe tener un font-size de font-size de 16 píxeles. + testString: 'assert($("p").css("font-size") == "16px", "Your p tag should have a font-size of 16 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. +

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-weight-for-multiple-heading-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-weight-for-multiple-heading-elements.spanish.md new file mode 100644 index 0000000000..d94b6a78c9 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-font-weight-for-multiple-heading-elements.spanish.md @@ -0,0 +1,94 @@ +--- +id: 587d781c367417b2b2512ac3 +title: Set the font-weight for Multiple Heading Elements +localeTitle: Establecer el peso de la fuente para varios elementos de encabezado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Establece el font-size de font-size de cada etiqueta de encabezado en el último desafío, aquí ajustará el font-weight la font-weight . +La propiedad font-weight establece la cantidad de caracteres gruesos o delgados en una sección del texto. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la propiedad font-weight para la etiqueta h1 en 800. + testString: 'assert($("h1").css("font-weight") == "800", "Your code should set the font-weight property for the h1 tag to 800.");' + - text: Su código debe establecer la propiedad font-weight para la etiqueta h2 en 600. + testString: 'assert($("h2").css("font-weight") == "600", "Your code should set the font-weight property for the h2 tag to 600.");' + - text: Su código debe establecer la propiedad font-weight para la etiqueta h3 en 500. + testString: 'assert($("h3").css("font-weight") == "500", "Your code should set the font-weight property for the h3 tag to 500.");' + - text: Su código debe establecer la propiedad font-weight para la etiqueta h4 en 400. + testString: 'assert($("h4").css("font-weight") == "400", "Your code should set the font-weight property for the h4 tag to 400.");' + - text: Su código debe establecer la propiedad font-weight para la etiqueta h5 en 300. + testString: 'assert($("h5").css("font-weight") == "300", "Your code should set the font-weight property for the h5 tag to 300.");' + - text: Su código debe establecer la propiedad font-weight para la etiqueta h6 en 200. + testString: 'assert($("h6").css("font-weight") == "200", "Your code should set the font-weight property for the h6 tag to 200.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

This is h1 text

+

This is h2 text

+

This is h3 text

+

This is h4 text

+
This is h5 text
+
This is h6 text
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-line-height-of-paragraphs.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-line-height-of-paragraphs.spanish.md new file mode 100644 index 0000000000..2e1f82d4fd --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/set-the-line-height-of-paragraphs.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d781d367417b2b2512ac5 +title: Set the line-height of Paragraphs +localeTitle: Establecer la línea de altura de los párrafos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+CSS ofrece la line-height propiedad para cambiar la altura de cada línea en un bloque de texto. Como sugiere su nombre, cambia la cantidad de espacio vertical que obtiene cada línea de texto. +
+ +## Instructions +
+Agregue una propiedad de line-height a la etiqueta p y establézcala en 25px. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la line-height de line-height de la etiqueta p en 25 píxeles. + testString: 'assert($("p").css("line-height") == "25px", "Your code should set the line-height of the p tag to 25 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. +

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-bezier-curve-to-move-a-graphic.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-bezier-curve-to-move-a-graphic.spanish.md new file mode 100644 index 0000000000..a039abded6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-bezier-curve-to-move-a-graphic.spanish.md @@ -0,0 +1,90 @@ +--- +id: 587d78a9367417b2b2512ae9 +title: Use a Bezier Curve to Move a Graphic +localeTitle: Use una curva Bezier para mover un gráfico +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Un desafío anterior discutió la palabra clave de ease-out que describe un cambio de animación que se acelera primero y luego se ralentiza al final de la animación. A la derecha, se muestra la diferencia entre la palabra clave de ease-out (para el elemento azul) y linear palabra clave linear (para el elemento rojo). Se pueden lograr progresiones de animación similares a la palabra clave de ease-out de uso utilizando una función de curva Bezier cúbica personalizada. +En general, el cambio de los puntos de anclaje p1 y p2 impulsa la creación de diferentes curvas Bezier, que controlan cómo avanza la animación a través del tiempo. Este es un ejemplo de una curva de Bezier que utiliza valores para imitar el estilo de relajación: +animation-timing-function: cubic-bezier(0, 0, 0.58, 1); +Recuerde que todas cubic-bezier funciones de cubic-bezier comienzan con p0 en (0, 0) y terminan con p3 en (1, 1). En este ejemplo, la curva se mueve más rápido a través del eje Y (comienza en 0, va a p1 y el valor de 0, luego va a p2 y el valor de 1) que se mueve a través del eje X (0 para comenzar, luego 0 para p1 , hasta 0.58 para p2 ). Como resultado, el cambio en el elemento animado progresa más rápido que el tiempo de la animación para ese segmento. Hacia el final de la curva, la relación entre el cambio en los valores de x e y se invierte: el valor de y se mueve de 1 a 1 (sin cambio), y los valores de x se mueven de 0.58 a 1, lo que hace que los cambios de animación progresen más lentamente en comparación La duración de la animación. +
+ +## Instructions +
+Para ver el efecto de esta curva de Bezier en acción, cambie la animation-timing-function de animation-timing-function del elemento con id de red a una función de cubic-bezier con x1, y1, x2, y2 valores establecidos respectivamente en 0, 0, 0.58, 1. Esto hará que ambos elementos progresen a través de la animación de manera similar. +
+ +## Tests +
+ +```yml +tests: + - text: 'El valor de la propiedad animation-timing-function del elemento con el id red debe ser una función de cubic-bezier con x1, y1, x2, y2 valores establecidos respectivamente en 0, 0, 0.58, 1.' + testString: 'assert($("#red").css("animation-timing-function") == "cubic-bezier(0, 0, 0.58, 1)", "The value of the animation-timing-function property of the element with the id red should be a cubic-bezier function with x1, y1, x2, y2 values set respectively to 0, 0, 0.58, 1 .");' + - text: El elemento con el ID red ya no debería tener la propiedad de animation-timing-function lineal. + testString: 'assert($("#red").css("animation-timing-function") !== "linear", "The element with the id red should no longer have the animation-timing-function property of linear.");' + - text: El valor de la propiedad de animation-timing-function para el elemento con el id blue no debe cambiar. + testString: 'assert($("#blue").css("animation-timing-function") == "ease-out", "The value of the animation-timing-function property for the element with the id blue should not change.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-css-linear-gradient-to-create-a-striped-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-css-linear-gradient-to-create-a-striped-element.spanish.md new file mode 100644 index 0000000000..d316dca5a7 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-a-css-linear-gradient-to-create-a-striped-element.spanish.md @@ -0,0 +1,87 @@ +--- +id: 587d78a5367417b2b2512ad7 +title: Use a CSS Linear Gradient to Create a Striped Element +localeTitle: Use un gradiente lineal de CSS para crear un elemento de rayas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La función de repeating-linear-gradient() es muy similar a linear-gradient() con la principal diferencia de que repite el patrón de gradiente especificado. repeating-linear-gradient() acepta una variedad de valores, pero por simplicidad, trabajará con un valor de ángulo y valores de parada de color en este desafío. +El valor del ángulo es la dirección del gradiente. Las paradas de color son como los valores de ancho que marcan el lugar donde se produce una transición, y se dan con un porcentaje o un número de píxeles. +En el ejemplo que se muestra en el editor de código, el degradado comienza con el color yellow en 0 píxeles, que se mezcla con el segundo color blue a 40 píxeles desde el principio. Dado que la siguiente parada de color también es de 40 píxeles, el degradado cambia inmediatamente al green tercer color, que a su vez se mezcla con el valor del color red ya que está a 80 píxeles del comienzo del degradado. +Para este ejemplo, es útil pensar en las paradas de color como pares donde cada dos colores se mezclan. +0px [yellow -- blend -- blue] 40px [green -- blend -- red] 80px +Si todos los valores de parada de dos colores son del mismo color, la mezcla no es perceptible porque está entre el mismo color, seguida de Transición difícil al siguiente color, por lo que terminas con rayas. +
+ +## Instructions +
+Haga rayas cambiando el repeating-linear-gradient() para usar un ángulo de gradiente de 45deg grados, luego establezca los dos primeros topes de color en yellow , y finalmente el segundo segundo color se detiene en black . +
+ +## Tests +
+ +```yml +tests: + - text: El ángulo del repeating-linear-gradient() debe ser de 45 grados. + testString: 'assert(code.match(/background:\s*?repeating-linear-gradient\(\s*?45deg/gi), "The angle of the repeating-linear-gradient() should be 45deg.");' + - text: El ángulo de la repeating-linear-gradient() ya no debe ser de 90 grados + testString: 'assert(!code.match(/90deg/gi), "The angle of the repeating-linear-gradient() should no longer be 90deg");' + - text: La parada de color en 0 píxeles debe ser yellow . + testString: 'assert(code.match(/yellow\s+?0(px)?/gi), "The color stop at 0 pixels should be yellow.");' + - text: Una parada de color a 40 píxeles debe ser yellow . + testString: 'assert(code.match(/yellow\s+?40px/gi), "One color stop at 40 pixels should be yellow.");' + - text: La segunda parada de color a 40 píxeles debe ser black . + testString: 'assert(code.match(/yellow\s+?40px,\s*?black\s+?40px/gi), "The second color stop at 40 pixels should be black.");' + - text: La última parada de color en 80 píxeles debe ser black . + testString: 'assert(code.match(/black\s+?80px/gi), "The last color stop at 80 pixels should be black.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "background: repeating-linear-gradient(45deg, yellow 0px, yellow 40px, black 40px, black 80px);" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-css-animation-to-change-the-hover-state-of-a-button.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-css-animation-to-change-the-hover-state-of-a-button.spanish.md new file mode 100644 index 0000000000..87abee18d6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-css-animation-to-change-the-hover-state-of-a-button.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d78a7367417b2b2512ae0 +title: Use CSS Animation to Change the Hover State of a Button +localeTitle: Usa la animación CSS para cambiar el estado de desplazamiento de un botón +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede usar CSS @keyframes para cambiar el color de un botón en su estado activo. +Aquí hay un ejemplo de cómo cambiar el ancho de una imagen al pasar el cursor: +
<style>
  img:hover {
    animation-name: width;
    animation-duration: 500ms;
  }

  @keyframes width {
    100% {
      width: 40px;
    }
  }
</style>

<img src="https://bit.ly/smallgooglelogo" alt="Google's Logo" />
+
+ +## Instructions +
+Tenga en cuenta que ms representa milisegundos, donde 1000 ms es igual a 1 s. +Use CSS @keyframes para cambiar el background-color de background-color del elemento del button para que se convierta en #4791d0 cuando un usuario se #4791d0 sobre él. La regla @keyframes solo debe tener una entrada para el 100% . +
+ +## Tests +
+ +```yml +tests: + - text: La regla @keyframes debe usar el animation-name de color de fondo. + testString: 'assert(code.match(/@keyframes\s+?background-color\s*?{/g), "The @keyframes rule should use the animation-name background-color.");' + - text: "Debería haber una regla en @keyframes que cambie el background-color a #4791d0 al 100%". + testString: 'assert(code.match(/100%\s*?{\s*?background-color:\s*?#4791d0;\s*?}/gi), "There should be one rule under @keyframes that changes the background-color to #4791d0 at 100%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewx-to-skew-an-element-along-the-x-axis.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewx-to-skew-an-element-along-the-x-axis.spanish.md new file mode 100644 index 0000000000..8f862ba70f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewx-to-skew-an-element-along-the-x-axis.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d78a6367417b2b2512adb +title: Use the CSS Transform Property skewX to Skew an Element Along the X-Axis +localeTitle: Utilice la propiedad CSS Transformar skewX para sesgar un elemento a lo largo del eje X +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La siguiente función de la propiedad de transform es skewX() , que desvía el elemento seleccionado a lo largo de su eje X (horizontal) en un grado determinado. +El siguiente código sesga el elemento de párrafo en -32 grados a lo largo del eje X. +
p {
  transform: skewX(-32deg);
}
+
+ +## Instructions +
+Inclina el elemento con la ID de bottom en 24 grados a lo largo del eje X usando la propiedad de transform . +
+ +## Tests +
+ +```yml +tests: + - text: El elemento con ID bottom debe estar sesgado 24 grados a lo largo de su eje X. + testString: 'assert(code.match(/#bottom\s*?{\s*?.*?\s*?transform:\s*?skewX\(24deg\);/g), "The element with id bottom should be skewed by 24 degrees along its X-axis.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "#bottom {background-color: blue; transform: skewX(24deg);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewy-to-skew-an-element-along-the-y-axis.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewy-to-skew-an-element-along-the-y-axis.spanish.md new file mode 100644 index 0000000000..15c98dae92 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-property-skewy-to-skew-an-element-along-the-y-axis.spanish.md @@ -0,0 +1,71 @@ +--- +id: 587d78a6367417b2b2512adc +title: Use the CSS Transform Property skewY to Skew an Element Along the Y-Axis +localeTitle: Utilice la propiedad de transformación de CSS sesgada para sesgar un elemento a lo largo del eje Y +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Dado que la función skewX() el elemento seleccionado a lo largo del eje X en un grado determinado, no es sorprendente que la propiedad skewY() un elemento a lo largo del eje Y (vertical). +
+ +## Instructions +
+Inclina el elemento con el id de top 10 grados top largo del eje Y utilizando la propiedad de transform . +
+ +## Tests +
+ +```yml +tests: + - text: El elemento con ID top debe estar sesgado en un ángulo de -10 grados a lo largo de su eje Y. + testString: 'assert(code.match(/#top\s*?{\s*?.*?\s*?transform:\s*?skewY\(-10deg\);/g), "The element with id top should be skewed by -10 degrees along its Y-axis.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "#top {background-color: red; transform: skewY(-10deg);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-change-the-size-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-change-the-size-of-an-element.spanish.md new file mode 100644 index 0000000000..3319732f7f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-change-the-size-of-an-element.spanish.md @@ -0,0 +1,80 @@ +--- +id: 587d78a5367417b2b2512ad9 +title: Use the CSS Transform scale Property to Change the Size of an Element +localeTitle: Use la propiedad de escala de transformación CSS para cambiar el tamaño de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para cambiar la escala de un elemento, CSS tiene la propiedad de transform , junto con su función scale() . El siguiente ejemplo de código duplica el tamaño de todos los elementos de párrafo en la página: +
p {
  transform:scale(2);
}
+
+ +## Instructions +
+Aumente el tamaño del elemento con el id de ball2 a 1.5 veces su tamaño original. +
+ +## Tests +
+ +```yml +tests: + - text: 'Establezca la propiedad de transform para #ball2 para escalarla 1.5 veces su tamaño.' + testString: 'assert(code.match(/#ball2\s*?{\s*?left:\s*?65%;\s*?transform:\s*?scale\(1\.5\);\s*?}|#ball2\s*?{\s*?transform:\s*?scale\(1\.5\);\s*?left:\s*?65%;\s*?}/gi), "Set the transform property for #ball2 to scale it 1.5 times its size.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "#ball2 {left: 65%; transform: scale(1.5);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-scale-an-element-on-hover.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-scale-an-element-on-hover.spanish.md new file mode 100644 index 0000000000..90a5dfbd16 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-css-transform-scale-property-to-scale-an-element-on-hover.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d78a5367417b2b2512ada +title: Use the CSS Transform scale Property to Scale an Element on Hover +localeTitle: Use la propiedad de escala de transformación CSS para escalar un elemento al pasar el cursor +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de transform tiene una variedad de funciones que le permiten escalar, mover, rotar, sesgar, etc., sus elementos. Cuando se usa con pseudoclases como :hover el :hover que especifican un determinado estado de un elemento, la propiedad de transform puede agregar fácilmente interactividad a sus elementos. +Aquí hay un ejemplo para escalar los elementos del párrafo a 2.1 veces su tamaño original cuando un usuario se cierne sobre ellos: +
p:hover {
  transform: scale(2.1);
}
+
+ +## Instructions +
+Añadir una regla CSS para el hover estado del div y utilizar el transform la propiedad para escalar la div elemento a 1,1 veces su tamaño original cuando un usuario se desplaza sobre él. +
+ +## Tests +
+ +```yml +tests: + - text: El tamaño del elemento div debe escalar 1.1 veces cuando el usuario se desplaza sobre él. + testString: 'assert(code.match(/div:hover\s*?{\s*?transform:\s*?scale\(1\.1\);/gi), "The size of the div element should scale 1.1 times when the user hovers over it.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "div:hover {transform: scale(1.1);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-em-tag-to-italicize-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-em-tag-to-italicize-text.spanish.md new file mode 100644 index 0000000000..a9dece83a2 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-em-tag-to-italicize-text.spanish.md @@ -0,0 +1,91 @@ +--- +id: 587d781a367417b2b2512ab9 +title: Use the em Tag to Italicize Text +localeTitle: Utilice la etiqueta em para cursiva texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para enfatizar texto, puedes usar la etiqueta em . Esto muestra el texto en cursiva, ya que el navegador aplica el CSS del font-style: italic; de font-style: italic; al elemento. +
+ +## Instructions +
+Envuelva una etiqueta em alrededor del contenido de la etiqueta de párrafo para darle énfasis. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una etiqueta em a la marca. + testString: 'assert($("em").length == 1, "Your code should add an em tag to the markup.");' + - text: La etiqueta em debe envolver el contenido de la etiqueta p pero no la etiqueta p sí misma. + testString: 'assert($("p").children().length == 1 && $("em").children().length == 2, "The em tag should wrap around the contents of the p tag but not the p tag itself.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-s-tag-to-strikethrough-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-s-tag-to-strikethrough-text.spanish.md new file mode 100644 index 0000000000..87d7fe225f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-s-tag-to-strikethrough-text.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d781b367417b2b2512aba +title: Use the s Tag to Strikethrough Text +localeTitle: Use la etiqueta s para tachar el texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para tachar el texto, que es cuando una línea horizontal corta los caracteres, puede usar la etiqueta s . Muestra que una sección de texto ya no es válida. Con la etiqueta s , el navegador aplica el CSS de text-decoration: line-through; al elemento. +
+ +## Instructions +
+Envuelva la etiqueta s alrededor de "Google" dentro de la etiqueta h4 y luego agregue la palabra Alfabeto a su lado, que no debería tener el formato tachado. +
+ +## Tests +
+ +```yml +tests: + - text: El código debería añadir una s etiqueta para el marcado. + testString: 'assert($("s").length == 1, "Your code should add one s tag to the markup.");' + - text: La etiqueta s debe envolver el texto de Google en la etiqueta h4 . No debe contener la palabra Alfabeto. + testString: 'assert($("s").text().match(/Google/gi) && !$("s").text().match(/Alphabet/gi), "A s tag should wrap around the Google text in the h4 tag. It should not contain the word Alphabet.");' + - text: 'Incluya la palabra Alfabeto en la etiqueta h4 , sin tachar el formato.' + testString: 'assert($("h4").html().match(/Alphabet/gi), "Include the word Alphabet in the h4 tag, without strikethrough formatting.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-strong-tag-to-make-text-bold.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-strong-tag-to-make-text-bold.spanish.md new file mode 100644 index 0000000000..928b91468a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-strong-tag-to-make-text-bold.spanish.md @@ -0,0 +1,93 @@ +--- +id: 587d781a367417b2b2512ab7 +title: Use the strong Tag to Make Text Bold +localeTitle: Utilice la etiqueta fuerte para hacer el texto en negrita +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para poner el texto en negrita, puede usar la etiqueta strong . Esto se usa a menudo para llamar la atención sobre el texto y simbolizar que es importante. Con la etiqueta strong , el navegador aplica el CSS de font-weight: bold; al elemento. +
+ +## Instructions +
+Envuelve una etiqueta strong alrededor de "Stanford University" dentro de la etiqueta p . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una etiqueta strong a la marca. + testString: 'assert($("strong").length == 1, "Your code should add one strong tag to the markup.");' + - text: La etiqueta strong debe estar dentro de la etiqueta p . + testString: 'assert($("p").children("strong").length == 1, "The strong tag should be inside the p tag.");' + - text: La etiqueta strong debe envolver alrededor de las palabras "Universidad de Stanford". + testString: 'assert($("strong").text().match(/^Stanford University$/gi), "The strong tag should wrap around the words "Stanford University".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-text-transform-property-to-make-text-uppercase.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-text-transform-property-to-make-text-uppercase.spanish.md new file mode 100644 index 0000000000..31bf09f817 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-text-transform-property-to-make-text-uppercase.spanish.md @@ -0,0 +1,101 @@ +--- +id: 587d781c367417b2b2512ac0 +title: Use the text-transform Property to Make Text Uppercase +localeTitle: Utilice la propiedad de transformación de texto para hacer mayúsculas de texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de text-transform en CSS se usa para cambiar la apariencia del texto. Es una forma conveniente de asegurarse de que el texto de una página web se muestre de forma coherente, sin tener que cambiar el contenido de texto de los elementos HTML reales. +La siguiente tabla muestra cómo los diferentes valores de text-transform cambian el texto de ejemplo "Transformarme". +
Valor Resultado
lowercase "transformame"
uppercase "Transfórmame"
capitalize "Transformame"
initial Usa el valor por defecto
inherit Use el valor de text-transform del elemento padre
none Predeterminado: usar el texto original
+
+ +## Instructions +
+Transforme el texto del h4 para que esté en mayúsculas utilizando la propiedad de text-transform . +
+ +## Tests +
+ +```yml +tests: + - text: El texto h4 debe estar en mayúsculas. + testString: 'assert($("h4").css("text-transform") === "uppercase", "The h4 text should be uppercase.");' + - text: El texto original del h4 no debe ser cambiado. + testString: 'assert(($("h4").text() !== $("h4").text().toUpperCase()), "The original text of the h4 should not be changed.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Alphabet

+
+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-u-tag-to-underline-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-u-tag-to-underline-text.spanish.md new file mode 100644 index 0000000000..a558d19602 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/applied-visual-design/use-the-u-tag-to-underline-text.spanish.md @@ -0,0 +1,92 @@ +--- +id: 587d781a367417b2b2512ab8 +title: Use the u Tag to Underline Text +localeTitle: Use la etiqueta u para subrayar el texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para subrayar el texto, puede utilizar la etiqueta u . Esto se usa a menudo para indicar que una sección del texto es importante, o algo para recordar. Con la etiqueta u , el navegador aplica el CSS de text-decoration: underline; al elemento. +
+ +## Instructions +
+Envuelva la etiqueta u únicamente alrededor del texto "Estudiantes de doctorado". +Nota
Intente evitar usar la etiqueta u cuando podría confundirse con un enlace. Las etiquetas de anclaje también tienen un formato subrayado predeterminado. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe agregar una etiqueta u a la marca. + testString: 'assert($("u").length === 1, "Your code should add a u tag to the markup.");' + - text: La etiqueta u debe envolver el texto "Estudiantes de doctorado". + testString: 'assert($("u").text() === "Ph.D. students", "The u tag should wrap around the text "Ph.D. students".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+

Google

+

Google was founded by Larry Page and Sergey Brin while they were Ph.D. students at Stanford University.

+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-a-negative-margin-to-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-a-negative-margin-to-an-element.spanish.md new file mode 100644 index 0000000000..f0bb52e5b6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-a-negative-margin-to-an-element.spanish.md @@ -0,0 +1,91 @@ +--- +id: bad87fee1348bd9aedf08823 +title: Add a Negative Margin to an Element +localeTitle: Agregar un margen negativo a un elemento +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-a-negative-margin-to-an-element' +videoUrl: '' +--- + +## Description +
+El margin un elemento controla la cantidad de espacio entre el border un elemento y los elementos circundantes. +Si establece el margin un elemento en un valor negativo, el elemento aumentará de tamaño. +
+ +## Instructions +
+Intente establecer el margin en un valor negativo como el del cuadro rojo. +Cambie el margin del cuadro azul a -15px , para que llene todo el ancho horizontal del cuadro amarillo que lo rodea. +
+ +## Tests +
+ +```yml +tests: + - text: Tu clase de blue-box debe dar elementos -15px de margin . + testString: 'assert($(".blue-box").css("margin-top") === "-15px", "Your blue-box class should give elements -15px of margin.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-borders-around-your-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-borders-around-your-elements.spanish.md new file mode 100644 index 0000000000..dcd07ee4d9 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-borders-around-your-elements.spanish.md @@ -0,0 +1,115 @@ +--- +id: bad87fee1348bd9bedf08813 +title: Add Borders Around Your Elements +localeTitle: Añadir bordes alrededor de sus elementos +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-borders-around-your-elements' +videoUrl: '' +--- + +## Description +
+Los bordes CSS tienen propiedades como style , color y width +Por ejemplo, si quisiéramos crear un borde rojo de 5 píxeles alrededor de un elemento HTML, podríamos usar esta clase: +
<style>
  .thin-red-border {
    border-color: red;
    border-width: 5px;
    border-style: solid;
  }
</style>
+
+ +## Instructions +
+Crea una clase llamada thick-green-border . Esta clase debe agregar un borde verde sólido de 10 px alrededor de un elemento HTML. Aplica la clase a tu foto de gato. +Recuerde que puede aplicar varias clases a un elemento utilizando su atributo de class , separando cada nombre de clase con un espacio. Por ejemplo: +<img class="class1 class2"> +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento img debería tener la clase smaller-image . + testString: 'assert($("img").hasClass("smaller-image"), "Your img element should have the class smaller-image.");' + - text: Tu elemento img debe tener la clase thick-green-border . + testString: 'assert($("img").hasClass("thick-green-border"), "Your img element should have the class thick-green-border.");' + - text: Dale a tu imagen un ancho de 10px de 10px . + testString: 'assert($("img").hasClass("thick-green-border") && parseInt($("img").css("border-top-width"), 10) >= 8 && parseInt($("img").css("border-top-width"), 10) <= 12, "Give your image a border width of 10px.");' + - text: Dale a tu imagen un estilo de borde solid . + testString: 'assert($("img").css("border-right-style") === "solid", "Give your image a border style of solid.");' + - text: El borde alrededor de su elemento img debe ser verde. + testString: 'assert($("img").css("border-left-color") === "rgb(0, 128, 0)", "The border around your img element should be green.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-margins-to-each-side-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-margins-to-each-side-of-an-element.spanish.md new file mode 100644 index 0000000000..bbbfbf3fa2 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-margins-to-each-side-of-an-element.spanish.md @@ -0,0 +1,96 @@ +--- +id: bad87fee1248bd9aedf08824 +title: Add Different Margins to Each Side of an Element +localeTitle: Añadir diferentes márgenes a cada lado de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+A veces querrá personalizar un elemento para que tenga un margin diferente en cada uno de sus lados. +CSS le permite controlar el margin de los cuatro lados individuales de un elemento con las propiedades margin-top , margin-right , margin-bottom y margin-left . +
+ +## Instructions +
+Dé a la caja azul un margin de 40px en su lado superior e izquierdo, pero solo 20px en su lado inferior y derecho. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar a la parte superior de los elementos 40px de margin . + testString: 'assert($(".blue-box").css("margin-top") === "40px", "Your blue-box class should give the top of elements 40px of margin.");' + - text: Su clase de blue-box debe otorgar el derecho de los elementos 20 20px de margin . + testString: 'assert($(".blue-box").css("margin-right") === "20px", "Your blue-box class should give the right of elements 20px of margin.");' + - text: Su clase de blue-box debe dar a la parte inferior de los elementos 20 20px de margin . + testString: 'assert($(".blue-box").css("margin-bottom") === "20px", "Your blue-box class should give the bottom of elements 20px of margin.");' + - text: Su clase de blue-box debe dar a la izquierda de los elementos 40px de margin . + testString: 'assert($(".blue-box").css("margin-left") === "40px", "Your blue-box class should give the left of elements 40px of margin.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element.spanish.md new file mode 100644 index 0000000000..f64550f59d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-different-padding-to-each-side-of-an-element.spanish.md @@ -0,0 +1,97 @@ +--- +id: bad87fee1348bd9aedf08824 +title: Add Different Padding to Each Side of an Element +localeTitle: Añadir diferente relleno a cada lado de un elemento +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-different-padding-to-each-side-of-an-element' +videoUrl: '' +--- + +## Description +
+A veces querrá personalizar un elemento para que tenga diferentes cantidades de padding en cada uno de sus lados. +CSS le permite controlar el padding de los cuatro lados individuales de un elemento con las propiedades padding-top , padding-right , padding-bottom y padding-left . +
+ +## Instructions +
+Dé a la caja azul un padding de 40px en su lado superior e izquierdo, pero solo 20px en su lado inferior y derecho. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar a la parte superior de los elementos 40px de padding . + testString: 'assert($(".blue-box").css("padding-top") === "40px", "Your blue-box class should give the top of the elements 40px of padding.");' + - text: Su clase de blue-box debe otorgar el derecho de los elementos 20px de padding . + testString: 'assert($(".blue-box").css("padding-right") === "20px", "Your blue-box class should give the right of the elements 20px of padding.");' + - text: Su clase de blue-box debe dar al fondo de los elementos 20px de padding . + testString: 'assert($(".blue-box").css("padding-bottom") === "20px", "Your blue-box class should give the bottom of the elements 20px of padding.");' + - text: Su clase de blue-box debe dar a la izquierda de los elementos 40px de padding . + testString: 'assert($(".blue-box").css("padding-left") === "40px", "Your blue-box class should give the left of the elements 40px of padding.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-rounded-corners-with-border-radius.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-rounded-corners-with-border-radius.spanish.md new file mode 100644 index 0000000000..74b77a7ee5 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/add-rounded-corners-with-border-radius.spanish.md @@ -0,0 +1,112 @@ +--- +id: bad87fee1348bd9aedf08814 +title: Add Rounded Corners with border-radius +localeTitle: Añadir esquinas redondeadas con radio de borde +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-rounded-corners-a-border-radius' +videoUrl: '' +--- + +## Description +
+Tu foto de gato tiene actualmente esquinas afiladas. Podemos redondear esas esquinas con una propiedad CSS llamada border-radius . +
+ +## Instructions +
+Puede especificar un border-radius con píxeles. Dale a tu foto de gato un border-radius de 10px de 10px . +Nota: este desafío permite múltiples soluciones posibles. Por ejemplo, puede agregar border-radius .thick-green-border clase .thick-green-border o a la clase .smaller-image . +
+ +## Tests +
+ +```yml +tests: + - text: El elemento de su imagen debe tener la clase "borde verde grueso". + testString: 'assert($("img").hasClass("thick-green-border"), "Your image element should have the class "thick-green-border".");' + - text: Su imagen debe tener un radio de borde de 10px + testString: 'assert(parseInt($("img").css("border-top-left-radius")) > 8, "Your image should have a border radius of 10px");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-margin-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-margin-of-an-element.spanish.md new file mode 100644 index 0000000000..31f9bbd49b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-margin-of-an-element.spanish.md @@ -0,0 +1,92 @@ +--- +id: bad87fee1348bd9aedf08822 +title: Adjust the Margin of an Element +localeTitle: Ajustar el margen de un elemento +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/adjust-the-margin-of-an-element' +videoUrl: '' +--- + +## Description +
+El margin un elemento controla la cantidad de espacio entre el border un elemento y los elementos circundantes. +Aquí, podemos ver que el cuadro azul y el cuadro rojo están anidados dentro del cuadro amarillo. Tenga en cuenta que el cuadro rojo tiene un margin más margin que el cuadro azul, lo que hace que parezca más pequeño. +Cuando aumenta el margin del cuadro azul, aumentará la distancia entre su borde y los elementos circundantes. +
+ +## Instructions +
+Cambie el margin del cuadro azul para que coincida con el del cuadro rojo. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar elementos de 20 20px de margin . + testString: 'assert($(".blue-box").css("margin-top") === "20px", "Your blue-box class should give elements 20px of margin.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-padding-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-padding-of-an-element.spanish.md new file mode 100644 index 0000000000..2d3a1170b5 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/adjust-the-padding-of-an-element.spanish.md @@ -0,0 +1,93 @@ +--- +id: bad88fee1348bd9aedf08825 +title: Adjust the Padding of an Element +localeTitle: Ajustar el relleno de un elemento +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/adjust-the-padding-of-an-element' +videoUrl: '' +--- + +## Description +
+Ahora vamos a guardar nuestra aplicación Cat Photo App por un tiempo y aprender más sobre el estilo HTML. +Es posible que ya hayas notado esto, pero todos los elementos HTML son esencialmente pequeños rectángulos. +Tres propiedades importantes controlan el espacio que rodea a cada elemento HTML: padding , margin y border . +El padding un elemento controla la cantidad de espacio entre el contenido del elemento y su border . +Aquí, podemos ver que el cuadro azul y el cuadro rojo están anidados dentro del cuadro amarillo. Tenga en cuenta que el cuadro rojo tiene más padding que el cuadro azul. +Cuando aumenta el padding del cuadro azul, aumentará la distancia ( padding ) entre el texto y el borde que lo rodea. +
+ +## Instructions +
+Cambie el padding de su caja azul para que coincida con el de su caja roja. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar elementos de padding 20px . + testString: 'assert($(".blue-box").css("padding-top") === "20px", "Your blue-box class should give elements 20px of padding.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/attach-a-fallback-value-to-a-css-variable.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/attach-a-fallback-value-to-a-css-variable.spanish.md new file mode 100644 index 0000000000..7a673ca2dc --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/attach-a-fallback-value-to-a-css-variable.spanish.md @@ -0,0 +1,264 @@ +--- +id: 5a9d7286424fe3d0e10cad13 +title: Attach a Fallback value to a CSS Variable +localeTitle: Adjuntar un valor de reserva a una variable CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Al usar su variable como un valor de propiedad CSS, puede adjuntar un valor de reserva al que su navegador volverá si la variable dada no es válida. +Nota: Este respaldo no se utiliza para aumentar la compatibilidad del navegador, y no funcionará en los navegadores IE. Más bien, se usa para que el navegador tenga un color para mostrar si no puede encontrar su variable. +Así es como lo haces: +
background: var(--penguin-skin, black);
+Esto establecerá el fondo en negro si su variable no se estableció. +Tenga en cuenta que esto puede ser útil para la depuración. +
+ +## Instructions +
+Parece que hay un problema con las variables proporcionadas a las .penguin-top y .penguin-bottom . En lugar de corregir el error tipográfico, agregue un valor alternativo de black a la propiedad de background de las .penguin-top y .penguin-bottom . +
+ +## Tests +
+ +```yml +tests: + - text: Aplique el valor de reserva de black a la propiedad de background de la clase penguin-top . + testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), "Apply the fallback value of black to the background property of the penguin-top class.");' + - text: Aplicar el valor de retorno de black al background propiedad del penguin-bottom la clase. + testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\(\s*?--pengiun-skin\s*?,\s*?black\s*?\)\s*?;[\s\S]*}/gi), "Apply the fallback value of black to the background property of the penguin-bottom class.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".penguin-top {background: var(--pengiun-skin, black);} .penguin-bottom {background: var(--pengiun-skin, black);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/cascading-css-variables.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/cascading-css-variables.spanish.md new file mode 100644 index 0000000000..4d73969331 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/cascading-css-variables.spanish.md @@ -0,0 +1,257 @@ +--- +id: 5a9d7295424fe3d0e10cad14 +title: Cascading CSS variables +localeTitle: Variables CSS en cascada +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Cuando crea una variable, queda disponible para que la use dentro del elemento en el que la creó. También está disponible dentro de cualquier elemento anidado dentro de él. Este efecto se conoce como cascada . +Debido a la cascada, las variables CSS a menudo se definen en el elemento : raíz . +:root es un selector de pseudo-clase que coincide con el elemento raíz del documento, generalmente el elemento. Al crear sus variables en :root , estarán disponibles globalmente y se podrá acceder a ellas desde cualquier otro selector más adelante en la hoja de estilo. +
+ +## Instructions +
+Defina una variable llamada --penguin-belly en el selector de :root y déle el valor de pink . Luego puede ver cómo el valor caerá en cascada para cambiar el valor a rosa, en cualquier lugar donde se use esa variable. +
+ +## Tests +
+ +```yml +tests: + - text: 'declara la variable --penguin-belly en la :root y --penguin-belly a pink '. + testString: 'assert(code.match(/:root\s*?{[\s\S]*--penguin-belly\s*?:\s*?pink\s*?;[\s\S]*}/gi), "declare the --penguin-belly variable in the :root and assign it to pink.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ":root {--penguin-belly: pink;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-a-variable-for-a-specific-area.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-a-variable-for-a-specific-area.spanish.md new file mode 100644 index 0000000000..a9e96a502f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-a-variable-for-a-specific-area.spanish.md @@ -0,0 +1,258 @@ +--- +id: 5a9d72a1424fe3d0e10cad15 +title: Change a variable for a specific area +localeTitle: Cambiar una variable para un área específica +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Cuando cree sus variables en :root , establecerán el valor de esa variable para toda la página. +Puede sobrescribir estas variables configurándolas nuevamente dentro de un elemento específico. +
+ +## Instructions +
+Cambie el valor de --penguin-belly a white en la clase de penguin . +
+ +## Tests +
+ +```yml +tests: + - text: La clase de penguin debe reasignar la variable --penguin-belly a white . + testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), "The penguin class should reassign the --penguin-belly variable to white.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".penguin {--penguin-belly: white;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-color-of-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-color-of-text.spanish.md new file mode 100644 index 0000000000..528ab8ceda --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-color-of-text.spanish.md @@ -0,0 +1,89 @@ +--- +id: bad87fee1348bd9aedf08803 +title: Change the Color of Text +localeTitle: Cambiar el color del texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Ahora vamos a cambiar el color de algunos de nuestros textos. +Podemos hacer esto cambiando el style de su elemento h2 . +La propiedad que es responsable del color del texto de un elemento es la propiedad de estilo de color . +Así es como establecería el color del texto de su elemento h2 en azul: +<h2 style="color: blue;">CatPhotoApp</h2> +Tenga en cuenta que es una buena práctica finalizar las declaraciones de style línea con una ; . +
+ +## Instructions +
+Cambia el estilo de tu elemento h2 para que su color de texto sea rojo. +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento h2 debe ser rojo. + testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your h2 element should be red.");' + - text: Su declaración de style debe terminar con un ; . + testString: 'assert(code.match(/\s*CatPhotoApp\s*<\/h2>/)," Your style declaration should end with a ; .");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-font-size-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-font-size-of-an-element.spanish.md new file mode 100644 index 0000000000..119e75b80f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/change-the-font-size-of-an-element.spanish.md @@ -0,0 +1,89 @@ +--- +id: bad87fee1348bd9aedf08806 +title: Change the Font Size of an Element +localeTitle: Cambiar el tamaño de fuente de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El tamaño de fuente se controla mediante la propiedad CSS de font-size , como esta: +
h1 {
  font-size: 30px;
}
+
+ +## Instructions +
+Dentro de la misma etiqueta <style> que contiene su clase de red-text , cree una entrada para los elementos p y establezca el font-size en 16 píxeles ( 16px ). +
+ +## Tests +
+ +```yml +tests: + - text: 'Entre las etiquetas de style , 16px elementos p font-size de font-size de 16px . El navegador y el zoom de texto deben estar al 100% ". + testString: 'assert(code.match(/p\s*{\s*font-size\s*:\s*16\s*px\s*;\s*}/i), "Between the style tags, give the p elements font-size of 16px. Browser and Text zoom should be at 100%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/create-a-custom-css-variable.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/create-a-custom-css-variable.spanish.md new file mode 100644 index 0000000000..a3f475e841 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/create-a-custom-css-variable.spanish.md @@ -0,0 +1,253 @@ +--- +id: 5a9d726c424fe3d0e10cad11 +title: Create a custom CSS Variable +localeTitle: Crear una variable CSS personalizada +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para crear una Variable CSS, solo debes darle un name con two dashes delante y asignarle un value como este: +
--penguin-skin: gray;
+Esto creará una variable llamada --penguin-skin y le asignará el valor de gray . +Ahora puede usar esa variable en otra parte de su CSS para cambiar el valor de otros elementos a gris. +
+ +## Instructions +
+En la clase de penguin , crea un nombre de variable --penguin-skin y dale un valor de gray +
+ +## Tests +
+ +```yml +tests: + - text: penguin clase penguin debe declarar la variable --penguin-skin y asignarla a gray . + testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), "penguin class should declare the --penguin-skin variable and assign it to gray.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".penguin {--penguin-skin: gray;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/give-a-background-color-to-a-div-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/give-a-background-color-to-a-div-element.spanish.md new file mode 100644 index 0000000000..bc55e10ef0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/give-a-background-color-to-a-div-element.spanish.md @@ -0,0 +1,115 @@ +--- +id: bad87fed1348bd9aede07836 +title: Give a Background Color to a div Element +localeTitle: Dar un color de fondo a un elemento div +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede establecer el color de fondo de un elemento con la propiedad de background-color . +Por ejemplo, si quisiera que el color de fondo de un elemento fuera green , lo pondría dentro de su elemento de style : +
.green-background {
  background-color: green;
}
+
+ +## Instructions +
+Crea una clase llamada silver-background con el background-color de background-color de plata. Asigna esta clase a tu elemento div . +
+ +## Tests +
+ +```yml +tests: + - text: Dale a tu elemento div la clase silver-background . + testString: 'assert($("div").hasClass("silver-background"), "Give your div element the class silver-background.");' + - text: Tu elemento div debe tener un fondo plateado. + testString: 'assert($("div").css("background-color") === "rgb(192, 192, 192)", "Your div element should have a silver background.");' + - text: Defina una clase llamada silver-background dentro del elemento de style y asigne el valor de silver a la propiedad de background-color . + testString: 'assert(code.match(/\.silver-background\s*{\s*background-color:\s*silver;\s*}/), "Define a class named silver-background within the style element and assign the value of silver to the background-color property.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/import-a-google-font.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/import-a-google-font.spanish.md new file mode 100644 index 0000000000..dc6234bcf2 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/import-a-google-font.spanish.md @@ -0,0 +1,106 @@ +--- +id: bad87fee1348bd9aedf08807 +title: Import a Google Font +localeTitle: Importar una fuente de Google +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Además de especificar las fuentes comunes que se encuentran en la mayoría de los sistemas operativos, también podemos especificar fuentes web no estándar y personalizadas para su uso en nuestro sitio web. Existen varias fuentes de fuentes web en Internet, pero, para este ejemplo, nos centraremos en la biblioteca de fuentes de Google. +Google Fonts es una biblioteca gratuita de fuentes web que puede usar en su CSS haciendo referencia a la URL de la fuente. +Entonces, sigamos adelante, importemos y apliquemos una fuente de Google (tenga en cuenta que si Google está bloqueado en su país, deberá saltarse este desafío). +Para importar una fuente de Google, puede copiar la URL de la (s) fuente (s) de la biblioteca de fuentes de Google y luego pegarla en su HTML. Para este desafío, importaremos la fuente Lobster . Para hacer esto, copie el siguiente fragmento de código y péguelo en la parte superior de su editor de código (antes del elemento de style apertura): +<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> +Ahora puedes usar la fuente Lobster en tu CSS usando Lobster como el FAMILY_NAME como en el siguiente ejemplo:
font-family: FAMILY_NAME, GENERIC_NAME; . +El GENERIC_NAME es opcional, y es una fuente alternativa en caso de que la otra fuente especificada no esté disponible. Esto está cubierto en el próximo desafío. +Los nombres de las familias distinguen entre mayúsculas y minúsculas y deben incluirse entre comillas si hay un espacio en el nombre. Por ejemplo, necesita citas para usar la fuente "Open Sans" , pero no para usar la fuente Lobster . +
+ +## Instructions +
+Cree una regla CSS de la font-family que use la fuente Lobster y asegúrese de que se aplicará a su elemento h2 . +
+ +## Tests +
+ +```yml +tests: + - text: Importar la fuente de la Lobster . + testString: 'assert(new RegExp("googleapis", "gi").test(code), "Import the Lobster font.");' + - text: Tu elemento h2 debe usar la fuente Lobster . + testString: 'assert($("h2").css("font-family").match(/lobster/i), "Your h2 element should use the font Lobster.");' + - text: Utilice un selector h2 CSS para cambiar la fuente. + testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\"|")?Lobster(\"|")?\s*;\s*\}/gi.test(code), "Use an h2 CSS selector to change the font.");' + - text: Tu elemento p debería seguir utilizando la fuente monospace . + testString: 'assert($("p").css("font-family").match(/monospace/i), "Your p element should still use the font monospace.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/improve-compatibility-with-browser-fallbacks.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/improve-compatibility-with-browser-fallbacks.spanish.md new file mode 100644 index 0000000000..e9fab4569f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/improve-compatibility-with-browser-fallbacks.spanish.md @@ -0,0 +1,67 @@ +--- +id: 5b7d72c338cd7e35b63f3e14 +title: Improve Compatibility with Browser Fallbacks +localeTitle: Mejora la compatibilidad con los fallbacks del navegador +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Al trabajar con CSS, es probable que tenga problemas de compatibilidad con el navegador en algún momento. Esta es la razón por la que es importante proporcionar interrupciones en el navegador para evitar posibles problemas. +Cuando su navegador analiza el CSS de una página web, ignora cualquier propiedad que no reconozca o admita. Por ejemplo, si usa una variable CSS para asignar un color de fondo en un sitio, Internet Explorer ignorará el color de fondo porque no admite las variables CSS. En ese caso, el navegador utilizará cualquier valor que tenga para esa propiedad. Si no puede encontrar ningún otro valor establecido para esa propiedad, volverá al valor predeterminado, que generalmente no es ideal. +Esto significa que si desea proporcionar un respaldo de navegador, es tan fácil como proporcionar otro valor más ampliamente admitido inmediatamente antes de su declaración. De esa manera, un navegador antiguo tendrá algo en lo que basarse, mientras que un navegador más nuevo simplemente interpretará cualquier declaración que se presente más adelante en la cascada. +
+ +## Instructions +
+Parece que se está utilizando una variable para establecer el color de fondo de la clase .red-box . Mejoremos la compatibilidad de nuestro navegador agregando otra declaración de background justo antes de la declaración existente y establezcamos su valor en rojo. +
+ +## Tests +
+ +```yml +tests: + - text: Su regla .red-box debe incluir una reserva con el background establecido en rojo inmediatamente antes de la declaración de background existente. + testString: 'assert(code.match(/.red-box\s*{[^}]*background:\s*(red|#ff0000|#f00|rgb\(\s*255\s*,\s*0\s*,\s*0\s*\)|rgb\(\s*100%\s*,\s*0%\s*,\s*0%\s*\)|hsl\(\s*0\s*,\s*100%\s*,\s*50%\s*\))\s*;\s*background:\s*var\(\s*--red-color\s*\);/gi), "Your .red-box rule should include a fallback with the background set to red immediately before the existing background declaration.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code=".red-box {background: red; background: var(--red-color);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/inherit-styles-from-the-body-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/inherit-styles-from-the-body-element.spanish.md new file mode 100644 index 0000000000..18f5ce2740 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/inherit-styles-from-the-body-element.spanish.md @@ -0,0 +1,72 @@ +--- +id: bad87fee1348bd9aedf08746 +title: Inherit Styles from the Body Element +localeTitle: Heredar estilos del elemento cuerpo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Ahora hemos comprobado que cada página HTML tiene un elemento de body , y que su elemento de body también se puede diseñar con CSS. +Recuerde, puede diseñar su elemento de body como cualquier otro elemento HTML, y todos los demás elementos heredarán los estilos de su elemento de body . +
+ +## Instructions +
+Primero, cree un elemento h1 con el texto Hello World +Luego, demos a todos los elementos en su página el color green agregando color: green; a la declaración de estilo de tu elemento body . +Finalmente, asigne a su elemento body la familia de fuentes de monospace agregando font-family: monospace; a la declaración de estilo de tu elemento body . +
+ +## Tests +
+ +```yml +tests: + - text: Crear un elemento h1 . + testString: 'assert(($("h1").length > 0), "Create an h1 element.");' + - text: Tu elemento h1 debería tener el texto Hello World . + testString: 'assert(($("h1").length > 0 && $("h1").text().match(/hello world/i)), "Your h1 element should have the text Hello World.");' + - text: Asegúrese de que su elemento h1 tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/h1>/g) && code.match(/

/g).length === code.match(/

h1 element has a closing tag.");' + - text: Dale a tu body elemento del color la propiedad de green . + testString: 'assert(($("body").css("color") === "rgb(0, 128, 0)"), "Give your body element the color property of green.");' + - text: Dale a tu elemento del body la propiedad font-family de monospace . + testString: 'assert(($("body").css("font-family").match(/monospace/i)), "Give your body element the font-family property of monospace.");' + - text: Su elemento h1 debería heredar la fuente monospace de su elemento de body . + testString: 'assert(($("h1").length > 0 && $("h1").css("font-family").match(/monospace/i)), "Your h1 element should inherit the font monospace from your body element.");' + - text: Su elemento h1 debe heredar el color verde de su elemento de body . + testString: 'assert(($("h1").length > 0 && $("h1").css("color") === "rgb(0, 128, 0)"), "Your h1 element should inherit the color green from your body element.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/make-circular-images-with-a-border-radius.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/make-circular-images-with-a-border-radius.spanish.md new file mode 100644 index 0000000000..882df5936c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/make-circular-images-with-a-border-radius.spanish.md @@ -0,0 +1,111 @@ +--- +id: bad87fee1348bd9aedf08815 +title: Make Circular Images with a border-radius +localeTitle: Hacer imágenes circulares con un radio de borde +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Además de los píxeles, también puede especificar el border-radius del border-radius usando un porcentaje. +
+ +## Instructions +
+Dale a tu foto de gato un border-radius de border-radius del 50% . +
+ +## Tests +
+ +```yml +tests: + - text: "Su imagen debe tener un radio de borde del 50% , por lo que es perfectamente circular". + testString: 'assert(parseInt($("img").css("border-top-left-radius")) > 48, "Your image should have a border radius of 50%, making it perfectly circular.");' + - text: Asegúrese de utilizar un valor porcentual del 50% . + testString: 'assert(code.match(/50%/g), "Be sure to use a percentage value of 50%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-all-other-styles-by-using-important.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-all-other-styles-by-using-important.spanish.md new file mode 100644 index 0000000000..2f2bd663bc --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-all-other-styles-by-using-important.spanish.md @@ -0,0 +1,83 @@ +--- +id: bad87fee1348bd9aedf07756 +title: Override All Other Styles by using Important +localeTitle: Anular todos los otros estilos usando Importante +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Yay! Acabamos de demostrar que los estilos en línea anularán todas las declaraciones de CSS en su elemento de style . +Pero espera. Hay una última forma de anular CSS. Este es el método más poderoso de todos. Pero antes de hacerlo, hablemos de por qué querría anular CSS. +En muchas situaciones, usarás bibliotecas CSS. Estos pueden anular accidentalmente su propio CSS. Entonces, cuando necesite estar absolutamente seguro de que un elemento tiene un CSS específico, puede usar !important +Volvamos a nuestra declaración de clase de pink-text . Recuerde que nuestra clase de pink-text fue anulada por las siguientes declaraciones de clase, declaraciones de id y estilos en línea. +
+ +## Instructions +
+¡Agreguemos la palabra clave !important para la declaración de color de su elemento de texto rosado para asegurarnos al 100% de que su elemento h1 será rosa. +Un ejemplo de cómo hacer esto es: +color: red !important; +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener la clase pink-text . + testString: 'assert($("h1").hasClass("pink-text"), "Your h1 element should have the class pink-text.");' + - text: Su elemento h1 debe tener la clase blue-text . + testString: 'assert($("h1").hasClass("blue-text"), "Your h1 element should have the class blue-text.");' + - text: Su elemento h1 debe tener el ID de orange-text . + testString: 'assert($("h1").attr("id") === "orange-text", "Your h1 element should have the id of orange-text.");' + - text: 'Su elemento h1 debe tener el estilo de color: white '. + testString: 'assert(code.match(/h1 element should have the inline style of color: white.");' + - text: Su declaración de clase de pink-text debe tener la palabra clave !important para anular todas las demás declaraciones. + testString: 'assert(code.match(/\.pink-text\s*?\{[\s\S]*?color:.*pink.*!important\s*;?[^\.]*\}/g), "Your pink-text class declaration should have the !important keyword to override all other declarations.");' + - text: Tu elemento h1 debe ser rosa. + testString: 'assert($("h1").css("color") === "rgb(255, 192, 203)", "Your h1 element should be pink.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

Hello World!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-by-styling-id-attributes.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-by-styling-id-attributes.spanish.md new file mode 100644 index 0000000000..d68dbf07e4 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-by-styling-id-attributes.spanish.md @@ -0,0 +1,84 @@ +--- +id: bad87fee1348bd8aedf06756 +title: Override Class Declarations by Styling ID Attributes +localeTitle: Anular declaraciones de clase por atributos de ID de estilo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Acabamos de demostrar que los navegadores leen CSS de arriba a abajo. Eso significa que, en caso de conflicto, el navegador utilizará la declaración de CSS que haya sido la última. +Pero aún no hemos terminado. Hay otras formas en que puedes anular CSS. ¿Recuerdas los atributos de identificación? +Anulemos sus clases de blue-text pink-text blue-text , y hagamos que su elemento h1 naranja, asignando una identificación al elemento h1 y luego diseñando un estilo. +
+ +## Instructions +
+Dale a tu elemento h1 el atributo id del orange-text . Recuerde, los estilos de identificación se ven así: +<h1 id="orange-text"> +Deje las clases de pink-text blue-text pink-text en su elemento h1 . +Cree una declaración CSS para su ID de orange-text en su elemento de style . Aquí hay un ejemplo de cómo se ve esto: +
#brown-text {
  color: brown;
}
+Nota: No importa si declara este CSS por encima o por debajo de la clase de texto rosado, ya que el atributo id siempre tendrá prioridad. +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener la clase pink-text . + testString: 'assert($("h1").hasClass("pink-text"), "Your h1 element should have the class pink-text.");' + - text: Su elemento h1 debe tener la clase blue-text . + testString: 'assert($("h1").hasClass("blue-text"), "Your h1 element should have the class blue-text.");' + - text: Dale a tu elemento h1 el id del orange-text . + testString: 'assert($("h1").attr("id") === "orange-text", "Give your h1 element the id of orange-text.");' + - text: Debería haber un solo elemento h1 . + testString: 'assert(($("h1").length === 1), "There should be only one h1 element.");' + - text: Crea una declaración CSS para tu ID de orange-text + testString: 'assert(code.match(/#orange-text\s*{/gi), "Create a CSS declaration for your orange-text id");' + - text: No le des a su h1 ningún style atributos. + testString: 'assert(!code.match(//gi), "Do not give your h1 any style attributes.");' + - text: Su elemento h1 debe ser naranja. + testString: 'assert($("h1").css("color") === "rgb(255, 165, 0)", "Your h1 element should be orange.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

Hello World!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-with-inline-styles.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-with-inline-styles.spanish.md new file mode 100644 index 0000000000..79827a8ed1 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-class-declarations-with-inline-styles.spanish.md @@ -0,0 +1,79 @@ +--- +id: bad87fee1348bd9aedf06756 +title: Override Class Declarations with Inline Styles +localeTitle: Anular declaraciones de clase con estilos en línea +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Por lo tanto, hemos comprobado que las declaraciones de identificación anulan las declaraciones de clase, independientemente de dónde estén declaradas en su elemento de style CSS. +Hay otras formas en que puede anular CSS. ¿Recuerdas los estilos en línea? +
+ +## Instructions +
+Use un inline style para tratar de hacer que nuestro elemento h1 blanco. Recuerde, los estilos de línea se ven así: +<h1 style="color: green;"> +Deje las clases de pink-text blue-text pink-text en su elemento h1 . +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener la clase pink-text . + testString: 'assert($("h1").hasClass("pink-text"), "Your h1 element should have the class pink-text.");' + - text: Su elemento h1 debe tener la clase blue-text . + testString: 'assert($("h1").hasClass("blue-text"), "Your h1 element should have the class blue-text.");' + - text: Su elemento h1 debe tener el ID de orange-text . + testString: 'assert($("h1").attr("id") === "orange-text", "Your h1 element should have the id of orange-text.");' + - text: Dale a tu elemento h1 un estilo en línea. + testString: 'assert(document.querySelector("h1[style]"), "Give your h1 element an inline style.");' + - text: Su elemento h1 debe ser blanco. + testString: 'assert($("h1").css("color") === "rgb(255, 255, 255)", "Your h1 element should be white.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

Hello World!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-styles-in-subsequent-css.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-styles-in-subsequent-css.spanish.md new file mode 100644 index 0000000000..b54927ef31 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/override-styles-in-subsequent-css.spanish.md @@ -0,0 +1,74 @@ +--- +id: bad87fee1348bd9aedf04756 +title: Override Styles in Subsequent CSS +localeTitle: Anular estilos en CSS subsiguiente +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Nuestra clase de "texto rosa" anuló la declaración CSS de nuestro elemento de body ! +Acabamos de demostrar que nuestras clases anularán el CSS del elemento del body . Entonces, la siguiente pregunta lógica es: ¿qué podemos hacer para anular nuestra clase de pink-text ? +
+ +## Instructions +
+Crea una clase CSS adicional llamada blue-text que le da a un elemento el color azul. Asegúrate de que esté debajo de tu declaración de clase de pink-text . +Aplique la clase de blue-text a su elemento h1 además de su clase de pink-text , y veamos cuál gana. +aplicación de múltiples atributos de clase a un elemento HTML se realiza con un espacio entre ellos como este: +class="class1 class2" +Nota: No importa en qué orden se enumeran las clases en el elemento HTML. +Sin embargo, lo que es importante es el orden de las declaraciones de class en la sección <style> . La segunda declaración siempre tendrá prioridad sobre la primera. Como .blue-text se declara en segundo lugar, anula los atributos de .pink-text +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener la clase pink-text . + testString: 'assert($("h1").hasClass("pink-text"), "Your h1 element should have the class pink-text.");' + - text: Su elemento h1 debe tener la clase blue-text . + testString: 'assert($("h1").hasClass("blue-text"), "Your h1 element should have the class blue-text.");' + - text: Tanto blue-text pink-text deben pertenecer al mismo elemento h1 . + testString: 'assert($(".pink-text").hasClass("blue-text"), "Both blue-text and pink-text should belong to the same h1 element.");' + - text: Su elemento h1 debe ser azul. + testString: 'assert($("h1").css("color") === "rgb(0, 0, 255)", "Your h1 element should be blue.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

Hello World!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/prioritize-one-style-over-another.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/prioritize-one-style-over-another.spanish.md new file mode 100644 index 0000000000..dfedf3d3fb --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/prioritize-one-style-over-another.spanish.md @@ -0,0 +1,66 @@ +--- +id: bad87fee1348bd9aedf08756 +title: Prioritize One Style Over Another +localeTitle: Priorizar un estilo sobre otro +challengeType: 0 +videoUrl: '' +--- + +## Description +
+A veces, sus elementos HTML recibirán múltiples estilos que entren en conflicto entre sí. +Por ejemplo, su elemento h1 no puede ser verde y rosa al mismo tiempo. +Veamos qué sucede cuando creamos una clase que hace que el texto sea rosa, luego lo aplicamos a un elemento. ¿Nuestra clase anulará el color: green; del elemento del body color: green; Propiedad CSS? +
+ +## Instructions +
+Crea una clase CSS llamada pink-text que le da a un elemento el color rosa. +Dale a tu elemento h1 la clase de pink-text . +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener la clase pink-text . + testString: 'assert($("h1").hasClass("pink-text"), "Your h1 element should have the class pink-text.");' + - text: 'Tu <style> debe tener una clase de CSS de pink-text que cambie el color .' + testString: 'assert(code.match(/\.pink-text\s*\{\s*color\s*:\s*.+\s*;\s*\}/g), "Your <style> should have a pink-text CSS class that changes the color.");' + - text: Tu elemento h1 debe ser rosa. + testString: 'assert($("h1").css("color") === "rgb(255, 192, 203)", "Your h1 element should be pink.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +

Hello World!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-font-family-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-font-family-of-an-element.spanish.md new file mode 100644 index 0000000000..e8ad5f7476 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-font-family-of-an-element.spanish.md @@ -0,0 +1,94 @@ +--- +id: bad87fee1348bd9aede08807 +title: Set the Font Family of an Element +localeTitle: Establecer la familia de fuentes de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede establecer qué fuente debe usar un elemento, usando la propiedad font-family . +Por ejemplo, si quisiera establecer la fuente de su elemento h2 en sans-serif , usaría el siguiente CSS: +
h2 {
  font-family: sans-serif;
}
+
+ +## Instructions +
+Haz que todos tus elementos p usen la fuente monospace . +
+ +## Tests +
+ +```yml +tests: + - text: Tus elementos p deberían usar la fuente monospace . + testString: 'assert($("p").not(".red-text").css("font-family").match(/monospace/i), "Your p elements should use the font monospace.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-id-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-id-of-an-element.spanish.md new file mode 100644 index 0000000000..148bb4a1b0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/set-the-id-of-an-element.spanish.md @@ -0,0 +1,118 @@ +--- +id: bad87eee1348bd9aede07836 +title: Set the id of an Element +localeTitle: Establecer la id de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Además de las clases, cada elemento HTML también puede tener un atributo id . +Existen varios beneficios de usar atributos de id : puede usar una id para diseñar un solo elemento y más adelante aprenderá que puede usarlos para seleccionar y modificar elementos específicos con JavaScript. +atributos de +id deben ser únicos. Los navegadores no harán cumplir esto, pero es una buena práctica ampliamente aceptada. Entonces, por favor, no le dé a más de un elemento el mismo atributo de id . +Aquí hay un ejemplo de cómo le das a tu elemento h2 el ID de cat-photo-app : +<h2 id="cat-photo-app"> +
+ +## Instructions +
+Dale a tu elemento de form la identificación cat-photo-form . +
+ +## Tests +
+ +```yml +tests: + - text: Dale a tu elemento de form la identificación de cat-photo-form . + testString: 'assert($("form").attr("id") === "cat-photo-form", "Give your form element the id of cat-photo-form.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/size-your-images.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/size-your-images.spanish.md new file mode 100644 index 0000000000..4ac32d2a42 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/size-your-images.spanish.md @@ -0,0 +1,103 @@ +--- +id: bad87fee1348bd9acdf08812 +title: Size Your Images +localeTitle: Tamaño de sus imágenes +challengeType: 0 +videoUrl: '' +--- + +## Description +
+CSS tiene una propiedad llamada width que controla el ancho de un elemento. Al igual que con las fuentes, usaremos px (píxeles) para especificar el ancho de la imagen. +Por ejemplo, si quisiéramos crear una clase CSS llamada larger-image que diera a los elementos HTML un ancho de 500 píxeles, usaríamos: +
<style>
  .larger-image {
    width: 500px;
  }
</style>
+
+ +## Instructions +
+Cree una clase llamada smaller-image y utilícela para cambiar el tamaño de la imagen de modo que tenga solo 100 píxeles de ancho. +Nota
Debido a las diferencias de implementación del navegador, es posible que tenga que estar al 100% del zoom para pasar las pruebas en este desafío. +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento img debería tener la clase smaller-image . + testString: 'assert($("img[src="https://bit.ly/fcc-relaxing-cat"]").attr("class") === "smaller-image", "Your img element should have the class smaller-image.");' + - text: Su imagen debe tener 100 píxeles de ancho. El zoom del navegador debe estar al 100%. + testString: 'assert($("img").width() === 100, "Your image should be 100 pixels wide. Browser zoom should be at 100%.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/specify-how-fonts-should-degrade.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/specify-how-fonts-should-degrade.spanish.md new file mode 100644 index 0000000000..e3f9b3c295 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/specify-how-fonts-should-degrade.spanish.md @@ -0,0 +1,110 @@ +--- +id: bad87fee1348bd9aedf08808 +title: Specify How Fonts Should Degrade +localeTitle: Especifique cómo deben degradarse las fuentes +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hay varias fuentes predeterminadas que están disponibles en todos los navegadores. Estas familias de fuentes genéricas incluyen monospace , serif y sans-serif +Cuando una fuente no está disponible, puede indicar al navegador que se "degrade" a otra fuente. +Por ejemplo, si deseaba que un elemento usara la fuente Helvetica , pero se degradara a la sans-serif cuando Helvetica no estaba disponible, la especificará de la siguiente manera: +
p {
  font-family: Helvetica, sans-serif;
}
+Los nombres genéricos de familia de fuentes no distinguen entre mayúsculas y minúsculas. Además, no necesitan comillas porque son palabras clave CSS. +
+ +## Instructions +
+Para empezar, aplique la fuente monospace al elemento h2 , de modo que ahora tenga dos fuentes: Lobster y monospace . +En el último desafío, importó la fuente Lobster usando la etiqueta de link . Ahora comente la importación de la fuente Lobster (utilizando los comentarios HTML que aprendió anteriormente) de Google Fonts para que ya no esté disponible. Observe cómo su elemento h2 se degrada a la fuente monospace . +Nota
Si tiene la fuente Lobster instalada en su computadora, no verá la degradación porque su navegador puede encontrar la fuente. +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento h2 debe usar la fuente Lobster . + testString: 'assert($("h2").css("font-family").match(/^"?lobster/i), "Your h2 element should use the font Lobster.");' + - text: Su elemento h2 debería degradarse a la fuente monospace cuando Lobster no está disponible. + testString: 'assert(/\s*h2\s*\{\s*font-family\:\s*(\"|")?Lobster(\"|")?,\s*monospace\s*;\s*\}/gi.test(code), "Your h2 element should degrade to the font monospace when Lobster is not available.");' + - text: Comente su llamada a Google para la fuente Lobster colocando <!-- delante de ella. ' + testString: 'assert(new RegExp("", "gi").test(code), "Be sure to close your comment by adding -->.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-multiple-elements-with-a-css-class.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-multiple-elements-with-a-css-class.spanish.md new file mode 100644 index 0000000000..8d03cd1fac --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-multiple-elements-with-a-css-class.spanish.md @@ -0,0 +1,96 @@ +--- +id: bad87fee1348bd9aefe08806 +title: Style Multiple Elements with a CSS Class +localeTitle: Estilo de elementos múltiples con una clase CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las clases le permiten usar los mismos estilos CSS en varios elementos HTML. Puedes ver esto aplicando tu clase de red-text al primer elemento p . +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento h2 debe ser rojo. + testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your h2 element should be red.");' + - text: Tu elemento h2 debe tener la clase red-text . + testString: 'assert($("h2").hasClass("red-text"), "Your h2 element should have the class red-text.");' + - text: Tu primer elemento p debe ser rojo. + testString: 'assert($("p:eq(0)").css("color") === "rgb(255, 0, 0)", "Your first p element should be red.");' + - text: Su segundo y tercer p elementos no deben ser rojos. + testString: 'assert(!($("p:eq(1)").css("color") === "rgb(255, 0, 0)") && !($("p:eq(2)").css("color") === "rgb(255, 0, 0)"), "Your second and third p elements should not be red.");' + - text: Tu primer elemento p debería tener la clase red-text . + testString: 'assert($("p:eq(0)").hasClass("red-text"), "Your first p element should have the class red-text.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-the-html-body-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-the-html-body-element.spanish.md new file mode 100644 index 0000000000..0522e886a5 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/style-the-html-body-element.spanish.md @@ -0,0 +1,61 @@ +--- +id: bad87fee1348bd9aedf08736 +title: Style the HTML Body Element +localeTitle: Estilo del elemento HTML del cuerpo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Ahora comencemos de nuevo y hablemos de la herencia CSS. +Cada página HTML tiene un elemento de body . +
+ +## Instructions +
+Podemos probar que el elemento del body existe aquí dándole un background-color de background-color de negro. +Podemos hacer esto agregando lo siguiente a nuestro elemento de style : +
body {
  background-color: black;
}
+
+ +## Tests +
+ +```yml +tests: + - text: Dale a tu elemento del body el background-color de background-color del negro. + testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Give your body element the background-color of black.");' + - text: Asegúrese de que su regla de CSS tenga el formato correcto para abrir y cerrar los corchetes. + testString: 'assert(code.match(/ +``` + + + + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/understand-absolute-versus-relative-units.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/understand-absolute-versus-relative-units.spanish.md new file mode 100644 index 0000000000..5cebf59223 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/understand-absolute-versus-relative-units.spanish.md @@ -0,0 +1,91 @@ +--- +id: bad82fee1322bd9aedf08721 +title: Understand Absolute versus Relative Units +localeTitle: Comprender unidades absolutas versus unidades relativas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los últimos varios desafíos establecen el margen o el relleno de un elemento con píxeles ( px ). Los píxeles son un tipo de unidad de longitud, que es lo que le dice al navegador cómo dimensionar o espaciar un elemento. Además de px , CSS tiene una serie de opciones de unidades de longitud diferentes que puede utilizar. +Los dos tipos principales de unidades de longitud son absolutos y relativos. Unidades absolutas vinculadas a unidades físicas de longitud. Por ejemplo, in y mm refieren a pulgadas y milímetros, respectivamente. Las unidades de longitud absoluta se aproximan a la medida real en una pantalla, pero hay algunas diferencias según la resolución de la pantalla. +Las unidades relativas, como em o rem , son relativas a otro valor de longitud. Por ejemplo, em se basa en el tamaño de la fuente de un elemento. Si lo usa para establecer la propiedad de font-size sí, es relativo al font-size de font-size . +Nota
Hay varias opciones de unidades relativas que están vinculadas al tamaño de la ventana gráfica. Están cubiertos en la sección Principios de diseño web responsivo. +
+ +## Instructions +
+Agregue una propiedad de padding al elemento con la clase red-box y 1.5em a 1.5em . +
+ +## Tests +
+ +```yml +tests: + - text: Tu clase de red-box debería tener una propiedad de padding . + testString: 'assert($(".red-box").css("padding-top") != "0px" && $(".red-box").css("padding-right") != "0px" && $(".red-box").css("padding-bottom") != "0px" && $(".red-box").css("padding-left") != "0px", "Your red-box class should have a padding property.");' + - text: Su clase de red-box debe dar elementos 1.5em de padding . + testString: 'assert(code.match(/\.red-box\s*?{\s*?.*?\s*?.*?\s*?padding:\s*?1\.5em/gi), "Your red-box class should give elements 1.5em of padding.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-css-class-to-style-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-css-class-to-style-an-element.spanish.md new file mode 100644 index 0000000000..58429be0e6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-css-class-to-style-an-element.spanish.md @@ -0,0 +1,101 @@ +--- +id: bad87fee1348bd9aecf08806 +title: Use a CSS Class to Style an Element +localeTitle: Usa una clase CSS para diseñar un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las clases son estilos reutilizables que se pueden agregar a elementos HTML. +Aquí hay un ejemplo de declaración de clase CSS: +
<style>
  .blue-text {
    color: blue;
  }
</style>
+Puede ver que hemos creado una clase CSS llamada blue-text dentro de la etiqueta <style> . +Puede aplicar una clase a un elemento HTML como este: +<h2 class="blue-text">CatPhotoApp</h2> +Tenga en cuenta que en su elemento de style CSS, los nombres de clase comienzan con un punto. En el atributo de clase de los elementos HTML, el nombre de la clase no incluye el período. +
+ +## Instructions +
+Dentro de su elemento de style , cambie el selector h2 a .red-text y actualice el valor del blue de blue a red . +Asigne a su elemento h2 el atributo de class con un valor de 'red-text' . +
+ +## Tests +
+ +```yml +tests: + - text: Tu elemento h2 debe ser rojo. + testString: 'assert($("h2").css("color") === "rgb(255, 0, 0)", "Your h2 element should be red.");' + - text: Tu elemento h2 debe tener la clase red-text . + testString: 'assert($("h2").hasClass("red-text"), "Your h2 element should have the class red-text.");' + - text: Su hoja de estilo debe declarar una clase de red-text y tener su color establecido en rojo. + testString: 'assert(code.match(/\.red-text\s*\{\s*color\s*:\s*red;\s*\}/g), "Your stylesheet should declare a red-text class and have its color set to red.");' + - text: 'No utilice declaraciones de estilo en línea como style="color: red" en su elemento h2 .' + testString: 'assert($("h2").attr("style") === undefined, "Do not use inline style declarations like style="color: red" in your h2 element.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-custom-css-variable.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-custom-css-variable.spanish.md new file mode 100644 index 0000000000..f31eca4132 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-custom-css-variable.spanish.md @@ -0,0 +1,272 @@ +--- +id: 5a9d727a424fe3d0e10cad12 +title: Use a custom CSS Variable +localeTitle: Use una variable CSS personalizada +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Después de crear su variable, puede asignar su valor a otras propiedades de CSS haciendo referencia al nombre que le dio. +
background: var(--penguin-skin);
+Esto cambiará el fondo de cualquier elemento que estés apuntando a gris porque ese es el valor de la variable --penguin-skin . +Tenga en cuenta que los estilos no se aplicarán a menos que los nombres de las variables coincidan exactamente. +
+ +## Instructions +
+Aplique la variable --penguin-skin a la propiedad de background de las clases penguin-top , penguin-bottom , right-hand y left-hand . +
+ +## Tests +
+ +```yml +tests: + - text: Aplique la variable --penguin-skin a la propiedad de background de la clase penguin-top . + testString: 'assert(code.match(/.penguin-top\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.penguin-bottom\s{/gi), "Apply the --penguin-skin variable to the background property of the penguin-top class.");' + - text: Aplicar la --penguin-skin variable al background propiedad del penguin-bottom la clase. + testString: 'assert(code.match(/.penguin-bottom\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.right-hand\s{/gi), "Apply the --penguin-skin variable to the background property of the penguin-bottom class.");' + - text: Aplique la variable --penguin-skin a la propiedad de background de la clase de la right-hand . + testString: 'assert(code.match(/.right-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}[\s\S]*.left-hand\s{/gi), "Apply the --penguin-skin variable to the background property of the right-hand class.");' + - text: Aplique la variable --penguin-skin a la propiedad de background de la clase de la left-hand . + testString: 'assert(code.match(/.left-hand\s*?{[\s\S]*background\s*?:\s*?var\s*?\(\s*?--penguin-skin\s*?\)\s*?;[\s\S]*}/gi), "Apply the --penguin-skin variable to the background property of the left-hand class.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".penguin-top {background: var(--penguin-skin);} .penguin-bottom {background: var(--penguin-skin);} .right-hand {background: var(--penguin-skin);} .left-hand {background: var(--penguin-skin);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-media-query-to-change-a-variable.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-media-query-to-change-a-variable.spanish.md new file mode 100644 index 0000000000..7684b8c00f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-a-media-query-to-change-a-variable.spanish.md @@ -0,0 +1,286 @@ +--- +id: 5a9d72ad424fe3d0e10cad16 +title: Use a media query to change a variable +localeTitle: Usa una consulta de medios para cambiar una variable +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las variables CSS pueden simplificar la forma en que utiliza las consultas de medios. +Por ejemplo, cuando su pantalla es más pequeña o más grande que el punto de interrupción de su consulta de medios, puede cambiar el valor de una variable y aplicará su estilo donde sea que se use. +
+ +## Instructions +
+En el :root selector de :root de la media query , cámbielo para que --penguin-size se redefina y se le dé un valor de 200px . Además, redefine --penguin-skin y dale un valor de black . Luego cambie el tamaño de la vista previa para ver este cambio en acción. +
+ +## Tests +
+ +```yml +tests: + - text: ' :root debe reasignar la variable --penguin-size a 200px .' + testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-size\s*?:\s*?200px\s*?;[\s\S]*}[\s\S]*}/gi), ":root should reassign the --penguin-size variable to 200px.");' + - text: ' :root debería reasignar la variable --penguin-skin a black '. + testString: 'assert(code.match(/media\s*?\(\s*?max-width\s*?:\s*?350px\s*?\)\s*?{[\s\S]*:root\s*?{[\s\S]*--penguin-skin\s*?:\s*?black\s*?;[\s\S]*}[\s\S]*}/gi), ":root should reassign the --penguin-skin variable to black.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "@media (max-width: 350px) {:root {--penguin-size: 200px; --penguin-skin: black;}}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-abbreviated-hex-code.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-abbreviated-hex-code.spanish.md new file mode 100644 index 0000000000..091adf2a3b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-abbreviated-hex-code.spanish.md @@ -0,0 +1,90 @@ +--- +id: bad87fee1348bd9aedf08719 +title: Use Abbreviated Hex Code +localeTitle: Use el código hexadecimal abreviado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Muchas personas se sienten abrumadas por las posibilidades de más de 16 millones de colores. Y es difícil recordar el código hexadecimal. Afortunadamente, puedes acortarlo. +Por ejemplo, el código hexadecimal de rojo #FF0000 se puede acortar a #F00 . Esta forma abreviada proporciona un dígito para el rojo, un dígito para el verde y un dígito para el azul. +Esto reduce el número total de colores posibles a alrededor de 4.000. Pero los navegadores interpretarán #FF0000 y #F00 como exactamente del mismo color. +
+ +## Instructions +
+Adelante, intente usar los códigos hexadecimales abreviados para colorear los elementos correctos. +
Color Código hexadecimal corto
Cian #0FF
Verde #0F0
rojo #F00
Fucsia #F0F
+
+ +## Tests +
+ +```yml +tests: + - text: ¡Da tu elemento h1 con el texto I am red! El color rojo. + testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your h1 element with the text I am red! the color red.");' + - text: 'Use el hex code abreviado para el color rojo en lugar del código hexadecimal #FF0000 .' + testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#F00\s*?;\s*?}/gi), "Use the abbreviate hex code for the color red instead of the hex code #FF0000.");' + - text: ¡Da tu elemento h1 con el texto I am green! El color verde. + testString: 'assert($(".green-text").css("color") === "rgb(0, 255, 0)", "Give your h1 element with the text I am green! the color green.");' + - text: 'Use el hex code abreviado para el color verde en lugar del código hexadecimal #00FF00 .' + testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#0F0\s*?;\s*?}/gi), "Use the abbreviated hex code for the color green instead of the hex code #00FF00.");' + - text: ¡Da tu elemento h1 con el texto I am cyan! El color cian. + testString: 'assert($(".cyan-text").css("color") === "rgb(0, 255, 255)", "Give your h1 element with the text I am cyan! the color cyan.");' + - text: 'Use el hex code abreviado para el color cian en lugar del código hexadecimal #00FFFF '. + testString: 'assert(code.match(/\.cyan-text\s*?{\s*?color:\s*?#0FF\s*?;\s*?}/gi), "Use the abbreviated hex code for the color cyan instead of the hex code #00FFFF.");' + - text: ¡Da tu elemento h1 con el texto I am fuchsia! El color fucsia. + testString: 'assert($(".fuchsia-text").css("color") === "rgb(255, 0, 255)", "Give your h1 element with the text I am fuchsia! the color fuchsia.");' + - text: 'Use el hex code abreviado para el color fucsia en lugar del código hexadecimal #FF00FF '. + testString: 'assert(code.match(/\.fuchsia-text\s*?{\s*?color:\s*?#F0F\s*?;\s*?}/gi), "Use the abbreviated hex code for the color fuchsia instead of the hex code #FF00FF.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

I am red!

+ +

I am fuchsia!

+ +

I am cyan!

+ +

I am green!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-an-id-attribute-to-style-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-an-id-attribute-to-style-an-element.spanish.md new file mode 100644 index 0000000000..a9db207ace --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-an-id-attribute-to-style-an-element.spanish.md @@ -0,0 +1,123 @@ +--- +id: bad87dee1348bd9aede07836 +title: Use an id Attribute to Style an Element +localeTitle: Use un atributo de ID para diseñar un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Una cosa interesante acerca de los atributos de id es que, al igual que las clases, puedes aplicarles un estilo usando CSS. +Sin embargo, una id no es reutilizable y solo debe aplicarse a un elemento. Una id también tiene una mayor especificidad (importancia) que una clase, por lo que si ambas se aplican al mismo elemento y tienen estilos en conflicto, se aplicarán los estilos de la id . +Aquí hay un ejemplo de cómo puedes tomar tu elemento con el atributo id de cat-photo-element y darle el color de fondo de verde. En su elemento de style : +
#cat-photo-element {
  background-color: green;
}
+Tenga en cuenta que dentro de su elemento de style , siempre hace referencia a las clases poniendo un . delante de sus nombres. Siempre hace referencia a los identificadores colocando un # delante de sus nombres. +
+ +## Instructions +
+Intente darle a su formulario, que ahora tiene el atributo id de cat-photo-form , un fondo verde. +
+ +## Tests +
+ +```yml +tests: + - text: Dale a tu elemento de form la identificación de cat-photo-form . + testString: 'assert($("form").attr("id") === "cat-photo-form", "Give your form element the id of cat-photo-form.");' + - text: Su elemento de form debe tener el background-color de background-color verde. + testString: 'assert($("#cat-photo-form").css("background-color") === "rgb(0, 128, 0)", "Your form element should have the background-color of green.");' + - text: Asegúrese de que su elemento de form tenga un atributo id . + testString: 'assert(code.match(//gi) && code.match(//gi).length > 0, "Make sure your form element has an id attribute.");' + - text: No le dé a su form ningún atributo de class o style . + testString: 'assert(!code.match(//gi) && !code.match(//gi), "Do not give your form any class or style attributes.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-attribute-selectors-to-style-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-attribute-selectors-to-style-elements.spanish.md new file mode 100644 index 0000000000..f34ebf934d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-attribute-selectors-to-style-elements.spanish.md @@ -0,0 +1,120 @@ +--- +id: 58c383d33e2e3259241f3076 +title: Use Attribute Selectors to Style Elements +localeTitle: Usar selectores de atributos para elementos de estilo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Ha estado asignando atributos de id o class a los elementos que desea diseñar específicamente. Estos son conocidos como ID y selectores de clase. Hay otros selectores de CSS que puede usar para seleccionar grupos personalizados de elementos para personalizar. +Veamos nuevamente CatPhotoApp para practicar el uso de los selectores de CSS. +Para este desafío, utilizará el selector de atributo [attr=value] para diseñar las casillas de verificación en CatPhotoApp. Este selector combina y diseña elementos con un valor de atributo específico. Por ejemplo, el código siguiente cambia los márgenes de todos los elementos con el type atributo y el valor de radio correspondiente: +
[type='radio'] {
  margin: 20px 0px 20px 0px;
}
+
+ +## Instructions +
+Con el selector de atributos de type , intente dar a las casillas de verificación en CatPhotoApp un margen superior de 10 px y un margen inferior de 15 px. +
+ +## Tests +
+ +```yml +tests: + - text: El selector de atributo de type debe usarse para seleccionar las casillas de verificación. + testString: 'assert(code.match(/ + +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + + + + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-margin-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-margin-of-an-element.spanish.md new file mode 100644 index 0000000000..a2bb234c66 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-margin-of-an-element.spanish.md @@ -0,0 +1,95 @@ +--- +id: bad87fee1348bd9afdf08726 +title: Use Clockwise Notation to Specify the Margin of an Element +localeTitle: Usar la notación de las agujas del reloj para especificar el margen de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Intentemos esto de nuevo, pero con margin esta vez. +En lugar de especificar individualmente las propiedades margin-top , margin-right , margin-bottom y margin-left un elemento, puede especificarlas todas en una línea, como esta: +margin: 10px 20px 10px 20px; +Estos cuatro valores funcionan como un reloj: arriba, derecha, abajo, izquierda, y producirán exactamente el mismo resultado que utilizando las instrucciones de margen específicas para cada lado. +
+ +## Instructions +
+Use la Clockwise Notation para dar al elemento con la clase de blue-box un margen de 40px en su parte superior e izquierda, pero solo 20 20px en su parte inferior derecha. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar a la parte superior de los elementos 40px de margin . + testString: 'assert($(".blue-box").css("margin-top") === "40px", "Your blue-box class should give the top of elements 40px of margin.");' + - text: Su clase de blue-box debe otorgar el derecho de los elementos 20 20px de margin . + testString: 'assert($(".blue-box").css("margin-right") === "20px", "Your blue-box class should give the right of elements 20px of margin.");' + - text: Su clase de blue-box debe dar a la parte inferior de los elementos 20 20px de margin . + testString: 'assert($(".blue-box").css("margin-bottom") === "20px", "Your blue-box class should give the bottom of elements 20px of margin.");' + - text: Su clase de blue-box debe dar a la izquierda de los elementos 40px de margin . + testString: 'assert($(".blue-box").css("margin-left") === "40px", "Your blue-box class should give the left of elements 40px of margin.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-padding-of-an-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-padding-of-an-element.spanish.md new file mode 100644 index 0000000000..b7353782f7 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-clockwise-notation-to-specify-the-padding-of-an-element.spanish.md @@ -0,0 +1,96 @@ +--- +id: bad87fee1348bd9aedf08826 +title: Use Clockwise Notation to Specify the Padding of an Element +localeTitle: Use la notación de las agujas del reloj para especificar el relleno de un elemento +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En lugar de especificar las propiedades padding-top , padding-right , padding-bottom y padding-left individualmente, puede especificarlas todas en una línea, como esta: +padding: 10px 20px 10px 20px; +Estos cuatro valores funcionan como un reloj: arriba, derecha, abajo, izquierda, y producirán exactamente el mismo resultado que utilizando las instrucciones de relleno específicas para cada lado. +
+ +## Instructions +
+Use la notación de las agujas del reloj para darle a la clase ".blue-box" un padding de 40px en su parte superior e izquierda, pero solo 20px en su parte inferior y derecha. +
+ +## Tests +
+ +```yml +tests: + - text: Su clase de blue-box debe dar a la parte superior de los elementos 40px de padding . + testString: 'assert($(".blue-box").css("padding-top") === "40px", "Your blue-box class should give the top of elements 40px of padding.");' + - text: Su clase de blue-box debe otorgar el derecho de los elementos 20px de padding . + testString: 'assert($(".blue-box").css("padding-right") === "20px", "Your blue-box class should give the right of elements 20px of padding.");' + - text: Su clase de blue-box debe dar al fondo de los elementos 20px de padding . + testString: 'assert($(".blue-box").css("padding-bottom") === "20px", "Your blue-box class should give the bottom of elements 20px of padding.");' + - text: Su clase de blue-box debe dar a la izquierda de los elementos 40px de padding . + testString: 'assert($(".blue-box").css("padding-left") === "40px", "Your blue-box class should give the left of elements 40px of padding.");' + - text: Debe usar la notación en el sentido de las agujas del reloj para configurar el relleno de la clase de blue-box . + testString: 'assert(!/padding-top|padding-right|padding-bottom|padding-left/.test(code), "You should use the clockwise notation to set the padding of blue-box class.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
margin
+ +
+
padding
+
padding
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-selectors-to-style-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-selectors-to-style-elements.spanish.md new file mode 100644 index 0000000000..b7c6f23a23 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-selectors-to-style-elements.spanish.md @@ -0,0 +1,97 @@ +--- +id: bad87fee1348bd9aedf08805 +title: Use CSS Selectors to Style Elements +localeTitle: Usar los selectores de CSS para elementos de estilo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Con CSS, hay cientos de properties CSS que puedes usar para cambiar la apariencia de un elemento en tu página. +Cuando ingresó <h2 style="color: red">CatPhotoApp</h2> , estaba diseñando ese elemento h2 individual con inline CSS , que significa Cascading Style Sheets . +Esa es una forma de especificar el estilo de un elemento, pero hay una mejor manera de aplicar CSS . +En la parte superior de su código, cree un bloque de style como este: +
<style>
</style>
+Dentro de ese bloque de estilo, puede crear un CSS selector para todos los elementos h2 . Por ejemplo, si desea que todos los elementos h2 sean rojos, debe agregar una regla de estilo que se vea así: +
<style>
  h2 {color: red;}
</style>
+Tenga en cuenta que es importante tener tanto la apertura como el cierre de llaves ( { y } ) alrededor de las reglas de estilo de cada elemento. También debe asegurarse de que la definición de estilo de su elemento se encuentre entre las etiquetas de estilo de apertura y de cierre. Finalmente, asegúrese de agregar un punto y coma al final de cada una de las reglas de estilo de su elemento. +
+ +## Instructions +
+Borre el atributo de estilo de su elemento h2 y, en su lugar, cree un bloque de style CSS. Agrega el CSS necesario para convertir todos los elementos h2 azul. +
+ +## Tests +
+ +```yml +tests: + - text: Elimine el atributo de estilo de su elemento h2 . + testString: 'assert(!$("h2").attr("style"), "Remove the style attribute from your h2 element.");' + - text: Crear un elemento de style . + testString: 'assert($("style") && $("style").length > 1, "Create a style element.");' + - text: Tu elemento h2 debe ser azul. + testString: 'assert($("h2").css("color") === "rgb(0, 0, 255)", "Your h2 element should be blue.");' + - text: Asegúrese de que la declaración h2 su hoja de estilo sea válida con un punto y coma y una llave de cierre. + testString: 'assert(code.match(/h2\s*\{\s*color\s*:.*;\s*\}/g), "Ensure that your stylesheet h2 declaration is valid with a semicolon and closing brace.");' + - text: Asegúrese de que todos sus elementos de style sean válidos y tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/style>/g) && code.match(/<\/style>/g).length === (code.match(//g) || []).length, "Make sure all your style elements are valid and have a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +
+

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-variables-to-change-several-elements-at-once.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-variables-to-change-several-elements-at-once.spanish.md new file mode 100644 index 0000000000..7e18d6792f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-css-variables-to-change-several-elements-at-once.spanish.md @@ -0,0 +1,258 @@ +--- +id: 5a9d725e424fe3d0e10cad10 +title: Use CSS Variables to change several elements at once +localeTitle: Usa las variables CSS para cambiar varios elementos a la vez +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las Variables CSS son una forma poderosa de cambiar muchas propiedades de estilo CSS a la vez cambiando solo un valor. +Siga las instrucciones a continuación para ver cómo cambiar solo tres valores puede cambiar el estilo de muchos elementos. +
+ +## Instructions +
+En la clase de penguin , cambie el valor de black a gray , el valor de gray a white y el de yellow a orange . +
+ +## Tests +
+ +```yml +tests: + - text: penguin clase penguin debe declarar la variable --penguin-skin y asignarla a gray . + testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-skin\s*?:\s*?gray\s*?;[\s\S]*}/gi), "penguin class should declare the --penguin-skin variable and assign it to gray.");' + - text: penguin clase penguin debe declarar la variable --penguin-belly y asignarla a white . + testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-belly\s*?:\s*?white\s*?;[\s\S]*}/gi), "penguin class should declare the --penguin-belly variable and assign it to white.");' + - text: penguin clase penguin debe declarar la variable --penguin-beak y asignarla a orange . + testString: 'assert(code.match(/.penguin\s*?{[\s\S]*--penguin-beak\s*?:\s*?orange\s*?;[\s\S]*}/gi), "penguin class should declare the --penguin-beak variable and assign it to orange.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".penguin {--penguin-skin: gray; --penguin-belly: white; --penguin-beak: orange;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-for-specific-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-for-specific-colors.spanish.md new file mode 100644 index 0000000000..0036830d2c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-for-specific-colors.spanish.md @@ -0,0 +1,61 @@ +--- +id: bad87fee1348bd9aedf08726 +title: Use Hex Code for Specific Colors +localeTitle: Use el código hexadecimal para colores específicos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+¿Sabías que hay otras formas de representar los colores en CSS? Una de estas formas se llama código hexadecimal, o hex code para abreviar. +Usualmente usamos decimals , o números de base 10, que usan los símbolos del 0 al 9 para cada dígito. Hexadecimals (o hex ) son números base 16. Esto significa que utiliza dieciséis símbolos distintos. Al igual que los decimales, los símbolos 0-9 representan los valores de cero a nueve. Luego, A, B, C, D, E, F representan los valores de diez a quince. En total, de 0 a F puede representar un dígito en hexadecimal , lo que nos da un total de 16 valores posibles. Puede encontrar más información sobre los números hexadecimales aquí . +En CSS, podemos usar 6 dígitos hexadecimales para representar los colores, dos para cada uno de los componentes rojo (R), verde (G) y azul (B). Por ejemplo, #000000 es negro y también es el valor más bajo posible. Puede encontrar más información sobre el sistema de color RGB aquí . +
body {
  color: #000000;
}
+
+ +## Instructions +
+Reemplace la palabra black en el color de fondo de nuestro elemento del body con su representación en hex code , #000000 . +
+ +## Tests +
+ +```yml +tests: + - text: Dale a tu elemento del body el color de fondo del negro. + testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Give your body element the background-color of black.");' + - text: Use el hex code para el color negro en lugar de la palabra black . + testString: 'assert(code.match(/body\s*{(([\s\S]*;\s*?)|\s*?)background.*\s*:\s*?#000(000)?((\s*})|(;[\s\S]*?}))/gi), "Use the hex code for the color black instead of the word black.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-to-mix-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-to-mix-colors.spanish.md new file mode 100644 index 0000000000..15a9e18b69 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-hex-code-to-mix-colors.spanish.md @@ -0,0 +1,92 @@ +--- +id: bad87fee1348bd9aedf08721 +title: Use Hex Code to Mix Colors +localeTitle: Usa el código hexadecimal para mezclar colores +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Para revisar, los códigos hexadecimales usan 6 dígitos hexadecimales para representar los colores, dos para cada uno de los componentes rojo (R), verde (G) y azul (B). +De estos tres colores puros (rojo, verde y azul), podemos variar las cantidades de cada uno para crear más de 16 millones de otros colores! +Por ejemplo, el naranja es rojo puro, mezclado con un poco de verde y sin azul. En código hexadecimal, esto se traduce en ser #FFA500 . +El dígito 0 es el número más bajo en código hexadecimal y representa una ausencia completa de color. +El dígito F es el número más alto en código hexadecimal y representa el brillo máximo posible. +
+ +## Instructions +
+Reemplace las palabras de color en nuestro elemento de style con sus códigos hexadecimales correctos. +
Color Código hexadecimal
Dodger Blue #1E90FF
Verde #00FF00
naranja #FFA500
rojo #FF0000
+
+ +## Tests +
+ +```yml +tests: + - text: ¡Da tu elemento h1 con el texto I am red! El color rojo. + testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your h1 element with the text I am red! the color red.");' + - text: Use el hex code para el color rojo en lugar de la palabra red . + testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?#FF0000\s*?;\s*?}/gi), "Use the hex code for the color red instead of the word red.");' + - text: ¡Da tu elemento h1 con el texto I am green! El color verde. + testString: 'assert($(".green-text").css("color") === "rgb(0, 255, 0)", "Give your h1 element with the text I am green! the color green.");' + - text: Use el hex code para el color verde en lugar de la palabra green . + testString: 'assert(code.match(/\.green-text\s*?{\s*?color:\s*?#00FF00\s*?;\s*?}/gi), "Use the hex code for the color green instead of the word green.");' + - text: ¡Da tu elemento h1 con el texto I am dodger blue! El color azul dodger. + testString: 'assert($(".dodger-blue-text").css("color") === "rgb(30, 144, 255)", "Give your h1 element with the text I am dodger blue! the color dodger blue.");' + - text: Use el hex code para el color azul de dodger en lugar de la palabra dodgerblue . + testString: 'assert(code.match(/\.dodger-blue-text\s*?{\s*?color:\s*?#1E90FF\s*?;\s*?}/gi), "Use the hex code for the color dodger blue instead of the word dodgerblue.");' + - text: ¡Da tu elemento h1 con el texto I am orange! El color naranja. + testString: 'assert($(".orange-text").css("color") === "rgb(255, 165, 0)", "Give your h1 element with the text I am orange! the color orange.");' + - text: Use el hex code para el color naranja en lugar de la palabra orange . + testString: 'assert(code.match(/\.orange-text\s*?{\s*?color:\s*?#FFA500\s*?;\s*?}/gi), "Use the hex code for the color orange instead of the word orange.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

I am red!

+ +

I am green!

+ +

I am dodger blue!

+ +

I am orange!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-to-mix-colors.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-to-mix-colors.spanish.md new file mode 100644 index 0000000000..f2b276d122 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-to-mix-colors.spanish.md @@ -0,0 +1,88 @@ +--- +id: bad82fee1348bd9aedf08721 +title: Use RGB to Mix Colors +localeTitle: Usa RGB para mezclar colores +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Al igual que con el código hexadecimal, puede mezclar colores en RGB utilizando combinaciones de diferentes valores. +
+ +## Instructions +
+Reemplace los códigos hexadecimales en nuestro elemento de style con sus valores RGB correctos. +
Color RGB
Azul rgb(0, 0, 255)
rojo rgb(255, 0, 0)
Orquídea rgb(218, 112, 214)
Tierra de siena rgb(160, 82, 45)
+
+ +## Tests +
+ +```yml +tests: + - text: ¡Da tu elemento h1 con el texto I am red! El color rojo. + testString: 'assert($(".red-text").css("color") === "rgb(255, 0, 0)", "Give your h1 element with the text I am red! the color red.");' + - text: Usa rgb para el color rojo. + testString: 'assert(code.match(/\.red-text\s*?{\s*?color:\s*?rgb\(\s*?255\s*?,\s*?0\s*?,\s*?0\s*?\)\s*?;\s*?}/gi), "Use rgb for the color red.");' + - text: ¡Da tu elemento h1 con el texto I am orchid! La orquídea de color . + testString: 'assert($(".orchid-text").css("color") === "rgb(218, 112, 214)", "Give your h1 element with the text I am orchid! the color orchid.");' + - text: Utilice rgb para la orquídea de color. + testString: 'assert(code.match(/\.orchid-text\s*?{\s*?color:\s*?rgb\(\s*?218\s*?,\s*?112\s*?,\s*?214\s*?\)\s*?;\s*?}/gi), "Use rgb for the color orchid.");' + - text: ¡Da tu elemento h1 con el texto I am blue! El color azul. + testString: 'assert($(".blue-text").css("color") === "rgb(0, 0, 255)", "Give your h1 element with the text I am blue! the color blue.");' + - text: Usa rgb para el color azul. + testString: 'assert(code.match(/\.blue-text\s*?{\s*?color:\s*?rgb\(\s*?0\s*?,\s*?0\s*?,\s*?255\s*?\)\s*?;\s*?}/gi), "Use rgb for the color blue.");' + - text: ¡Da tu elemento h1 con el texto I am sienna! el color siena. + testString: 'assert($(".sienna-text").css("color") === "rgb(160, 82, 45)", "Give your h1 element with the text I am sienna! the color sienna.");' + - text: Usa rgb para el color siena. + testString: 'assert(code.match(/\.sienna-text\s*?{\s*?color:\s*?rgb\(\s*?160\s*?,\s*?82\s*?,\s*?45\s*?\)\s*?;\s*?}/gi), "Use rgb for the color sienna.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

I am red!

+ +

I am orchid!

+ +

I am sienna!

+ +

I am blue!

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-values-to-color-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-values-to-color-elements.spanish.md new file mode 100644 index 0000000000..a57ab86995 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-css/use-rgb-values-to-color-elements.spanish.md @@ -0,0 +1,66 @@ +--- +id: bad87fee1348bd9aede08718 +title: Use RGB values to Color Elements +localeTitle: Usar valores RGB para elementos de color +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Otra forma de representar los colores en CSS es mediante el uso de valores RGB . +El valor RGB para negro se ve así: +rgb(0, 0, 0) +El valor RGB para blanco se ve así: +rgb(255, 255, 255) +En lugar de usar seis dígitos hexadecimales como lo hace con hexadecimal código, con RGB especifique el brillo de cada color con un número entre 0 y 255. +Si hace los cálculos, los dos dígitos de un color son 16 por 16, lo que nos da 256 valores totales. Entonces, RGB , que comienza a contar desde cero, tiene exactamente el mismo número de valores posibles que el código hexadecimal. +Aquí hay un ejemplo de cómo cambiarías el fondo del cuerpo a naranja usando su código RGB. +
body {
  background-color: rgb(255, 165, 0);
}
+
+ +## Instructions +
+Reemplazemos el código hexadecimal en el color de fondo de nuestro elemento del body con el valor RGB para negro: rgb(0, 0, 0) +
+ +## Tests +
+ +```yml +tests: + - text: El elemento de tu body debe tener un fondo negro. + testString: 'assert($("body").css("background-color") === "rgb(0, 0, 0)", "Your body element should have a black background.");' + - text: Usa rgb para darle a tu body un color negro. + testString: 'assert(code.match(/rgb\s*\(\s*0\s*,\s*0\s*,\s*0\s*\)/ig), "Use rgb to give your body element a color of black.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-a-submit-button-to-a-form.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-a-submit-button-to-a-form.spanish.md new file mode 100644 index 0000000000..dd8585837e --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-a-submit-button-to-a-form.spanish.md @@ -0,0 +1,82 @@ +--- +id: bad87fee1348bd9aedd08830 +title: Add a Submit Button to a Form +localeTitle: Agregar un botón de envío a un formulario +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-a-submit-button-to-a-form' +videoUrl: '' +--- + +## Description +
+Agreguemos un botón de submit a su formulario. Al hacer clic en este botón, los datos de su formulario se enviarán a la URL que especificó con el atributo de action su formulario. +Aquí hay un ejemplo de botón de envío: +<button type="submit">this button submits the form</button> +
+ +## Instructions +
+Agregue un botón como el último elemento de su elemento de form con un tipo de submit y "Enviar" como texto. +
+ +## Tests +
+ +```yml +tests: + - text: Su formulario debe tener un botón en su interior. + testString: 'assert($("form").children("button").length > 0, "Your form should have a button inside it.");' + - text: El botón de envío debe tener el atributo type establecido en submit . + testString: 'assert($("button").attr("type") === "submit", "Your submit button should have the attribute type set to submit.");' + - text: Su botón de enviar solo debe tener el texto "Enviar". + testString: 'assert($("button").text().match(/^\s*submit\s*$/gi), "Your submit button should only have the text "Submit".");' + - text: Asegúrese de que su elemento button tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.spanish.md new file mode 100644 index 0000000000..ef8ef5cbfb --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-images-to-your-website.spanish.md @@ -0,0 +1,75 @@ +--- +id: bad87fee1348bd9aedf08812 +title: Add Images to Your Website +localeTitle: Añadir imágenes a su sitio web +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-images-to-your-website' +videoUrl: '' +--- + +## Description +
+Puede agregar imágenes a su sitio web usando el elemento img , y apuntar a la URL de una imagen específica usando el atributo src . +Un ejemplo de esto sería: +<img src="https://www.your-image-source.com/your-image.jpg"> +Tenga en cuenta que los elementos img se cierran automáticamente. +Todos los elementos img deben tener un atributo alt . El texto dentro de un atributo alt se usa para que los lectores de pantalla mejoren la accesibilidad y se muestra si la imagen no se carga. +Nota: Si la imagen es puramente decorativa, usar un atributo alt vacío es una buena práctica. +Idealmente, el atributo alt no debe contener caracteres especiales a menos que sea necesario. +Vamos a añadir un alt atributo a nuestra img ejemplo anterior: +<img src="https://www.your-image-source.com/your-image.jpg" alt="Author standing on a beach with two thumbs up."> +
+ +## Instructions +
+Intentemos agregar una imagen a nuestro sitio web: +Inserte una etiqueta img , antes del elemento h2 . +Ahora establezca el atributo src para que apunte a esta url: +https://bit.ly/fcc-relaxing-cat +Finalmente, no se olvide de darle a su imagen un texto alt . +
+ +## Tests +
+ +```yml +tests: + - text: Tu página debe tener un elemento de imagen. + testString: 'assert($("img").length > 0, "Your page should have an image element.");' + - text: Su imagen debe tener un atributo src que apunta a la imagen del gatito. + testString: 'assert(new RegExp("\/\/bit.ly\/fcc-relaxing-cat|\/\/s3.amazonaws.com\/freecodecamp\/relaxing-cat.jpg", "gi").test($("img").attr("src")), "Your image should have a src attribute that points to the kitten image.");' + - text: Su elemento de imagen debe tener un atributo alt . + testString: 'assert(code.match(/alt\s*?=\s*?(\"|\").*(\"|\")/), "Your image element must have an alt attribute.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+ + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.spanish.md new file mode 100644 index 0000000000..3fd482f0f1 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/add-placeholder-text-to-a-text-field.spanish.md @@ -0,0 +1,78 @@ +--- +id: bad87fee1348bd9aedf08830 +title: Add Placeholder Text to a Text Field +localeTitle: Añadir texto de marcador de posición a un campo de texto +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/add-placeholder-text-to-a-text-field' +videoUrl: '' +--- + +## Description +
+texto de marcador de posición es lo que se muestra en su elemento de input antes de que su usuario haya ingresado algo. +Puede crear texto de marcador de posición de la siguiente manera: +<input type="text" placeholder="this is placeholder text"> +
+ +## Instructions +
+Establezca el valor del placeholder de placeholder de su input texto en "URL de foto de gato". +
+ +## Tests +
+ +```yml +tests: + - text: Agregue un atributo de placeholder al elemento de input texto existente. + testString: 'assert($("input[placeholder]").length > 0, "Add a placeholder attribute to the existing text input element.");' + - text: Establezca el valor de su atributo de marcador de posición en "URL de foto de gato". + testString: 'assert($("input") && $("input").attr("placeholder") && $("input").attr("placeholder").match(/cat\s+photo\s+URL/gi), "Set the value of your placeholder attribute to "cat photo URL".");' + - text: El elemento de input terminado debe tener una sintaxis válida. + testString: 'assert($("input[type=text]").length > 0 && code.match(/\s]+))?)+\s*|\s*)\/?>/gi), "The finished input element should have valid syntax.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+ +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/check-radio-buttons-and-checkboxes-by-default.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/check-radio-buttons-and-checkboxes-by-default.spanish.md new file mode 100644 index 0000000000..d8ed848c78 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/check-radio-buttons-and-checkboxes-by-default.spanish.md @@ -0,0 +1,83 @@ +--- +id: bad87fee1348bd9aedd08835 +title: Check Radio Buttons and Checkboxes by Default +localeTitle: Comprobar botones de radio y casillas de verificación por defecto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede configurar una casilla de verificación o un botón de opción para que se marque de forma predeterminada utilizando el atributo checked . +Para hacer esto, simplemente agregue la palabra "marcado" al interior de un elemento de entrada. Por ejemplo: +<input type="radio" name="test-name" checked> +
+ +## Instructions +
+Establezca el primero de sus radio buttons y el primero de sus checkboxes de checkboxes para que ambos estén marcados de forma predeterminada. +
+ +## Tests +
+ +```yml +tests: + - text: Su primer botón de radio en su formulario debe ser verificado por defecto. + testString: 'assert($("input[type="radio"]").prop("checked"), "Your first radio button on your form should be checked by default.");' + - text: Su primera casilla de verificación en su formulario debe estar marcada por defecto. + testString: 'assert($("input[type="checkbox"]").prop("checked"), "Your first checkbox on your form should be checked by default.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/comment-out-html.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/comment-out-html.spanish.md new file mode 100644 index 0000000000..feb79097a9 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/comment-out-html.spanish.md @@ -0,0 +1,67 @@ +--- +id: bad87fee1348bd9aedf08804 +title: Comment out HTML +localeTitle: Comentar fuera de HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Recuerde que para iniciar un comentario, debe usar <!-- y para finalizar un comentario, debe usar --> +Aquí deberá finalizar el comentario antes de que comience su elemento h2 . +
+ +## Instructions +
+Comente su elemento h1 y su elemento p , pero no su elemento h2 . +
+ +## Tests +
+ +```yml +tests: + - text: Comenta tu elemento h1 para que no se vea en tu página. + testString: 'assert(($("h1").length === 0), "Comment out your h1 element so that it is not visible on your page.");' + - text: Deje su elemento h2 comentarios para que sea visible en su página. + testString: 'assert(($("h2").length > 0), "Leave your h2 element uncommented so that it is visible on your page.");' + - text: Comenta tu elemento p para que no se vea en tu página. + testString: 'assert(($("p").length === 0), "Comment out your p element so that it is not visible on your page.");' + - text: 'Asegúrese de cerrar cada uno de sus comentarios con --> .' + testString: 'assert(code.match(/[^fc]-->/g).length > 1, "Be sure to close each of your comments with -->.");' + - text: No cambie el orden de h1 h2 o p en el código. + testString: 'assert((code.match(/<([a-z0-9]){1,2}>/g)[0]==="

" && code.match(/<([a-z0-9]){1,2}>/g)[1]==="

" && code.match(/<([a-z0-9]){1,2}>/g)[2]==="

") , "Do not change the order of the h1 h2 or p in the code.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-bulleted-unordered-list.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-bulleted-unordered-list.spanish.md new file mode 100644 index 0000000000..68ba7dd957 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-bulleted-unordered-list.spanish.md @@ -0,0 +1,70 @@ +--- +id: bad87fee1348bd9aedf08827 +title: Create a Bulleted Unordered List +localeTitle: Crear una lista desordenada con viñetas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML tiene un elemento especial para crear unordered lists o listas de estilo de punto de viñeta. +listas desordenadas comienzan con un elemento <ul> apertura, seguido de cualquier número de elementos <li> . Finalmente, las listas desordenadas se cierran con un </ul> +Por ejemplo: +
<ul>
  <li>milk</li>
  <li>cheese</li>
</ul>
+crearía una lista de estilo de punto de bala de "leche" y "queso". +
+ +## Instructions +
+Elimine los dos últimos elementos p y cree una lista desordenada de tres cosas que los gatos adoran al final de la página. +
+ +## Tests +
+ +```yml +tests: + - text: Crear un elemento ul . + testString: 'assert($("ul").length > 0, "Create a ul element.");' + - text: Debes tener tres elementos li dentro de tu elemento ul . + testString: 'assert($("ul li").length > 2, "You should have three li elements within your ul element.");' + - text: Asegúrese de que su elemento ul tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/ul>/gi) && code.match(/
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-form-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-form-element.spanish.md new file mode 100644 index 0000000000..fd5345693b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-form-element.spanish.md @@ -0,0 +1,77 @@ +--- +id: bad87fee1348bd9aede08830 +title: Create a Form Element +localeTitle: Crear un elemento de formulario +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede crear formularios web que realmente envíen datos a un servidor usando nada más que HTML puro. Puedes hacer esto especificando una acción en tu elemento de form . +Por ejemplo: +<form action="/url-where-you-want-to-submit-form-data"></form> +
+ +## Instructions +
+Anide el campo de texto dentro de un elemento de form y agrega el atributo action="/submit-cat-photo" al elemento de formulario. +
+ +## Tests +
+ +```yml +tests: + - text: Anida el elemento de entrada de texto dentro de un elemento de form . + testString: 'assert($("form") && $("form").children("input") && $("form").children("input").length > 0, "Nest your text input element within a form element.");' + - text: Asegúrese de que su form tenga un atributo de action que esté establecido en /submit-cat-photo + testString: 'assert($("form").attr("action") === "/submit-cat-photo", "Make sure your form has an action attribute which is set to /submit-cat-photo");' + - text: Asegúrese de que su elemento de form tenga etiquetas de apertura y cierre bien formadas. + testString: 'assert(code.match(/<\/form>/g) && code.match(/
/g) && code.match(/<\/form>/g).length === code.match(//g).length, "Make sure your form element has well-formed open and close tags.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+ +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-checkboxes.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-checkboxes.spanish.md new file mode 100644 index 0000000000..049b04aeaa --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-checkboxes.spanish.md @@ -0,0 +1,88 @@ +--- +id: bad87fee1348bd9aedf08835 +title: Create a Set of Checkboxes +localeTitle: Crear un conjunto de casillas de verificación +challengeType: 0 +videoUrl: '' +--- + +## Description +
+formularios suelen utilizar checkboxes de checkboxes para preguntas que pueden tener más de una respuesta. +casillas de verificación son un tipo de input +Cada una de sus casillas de verificación se puede anidar dentro de su propio elemento de label . Al ajustar un elemento de input dentro de un elemento de label , asociará automáticamente la entrada de la casilla de verificación con el elemento de etiqueta que lo rodea. +Todas las entradas de las casillas de verificación relacionadas deben tener el mismo atributo de name . +Se considera una buena práctica definir explícitamente la relación entre una input casilla de verificación y su label correspondiente estableciendo el atributo for en el elemento de label para que coincida con el atributo id del elemento de input asociado. +Aquí hay un ejemplo de una casilla de verificación: +<label for="loving"><input id="loving" type="checkbox" name="personality"> Loving</label> +
+ +## Instructions +
+Agregue a su formulario un conjunto de tres casillas de verificación. Cada casilla de verificación debe estar anidada dentro de su propio elemento de label . Los tres deben compartir el atributo de name de la personality . +
+ +## Tests +
+ +```yml +tests: + - text: Su página debe tener tres elementos de casilla de verificación. + testString: 'assert($("input[type="checkbox"]").length > 2, "Your page should have three checkbox elements.");' + - text: Cada uno de sus tres elementos de casilla de verificación debe estar anidado en su propio elemento etiqueta . + testString: 'assert($("label > input[type="checkbox"]:only-child").length > 2, "Each of your three checkbox elements should be nested in its own label element.");' + - text: Asegúrese de que cada uno de sus elementos label tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/label>/g) && code.match(/
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+ + +
+ + + +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-radio-buttons.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-radio-buttons.spanish.md new file mode 100644 index 0000000000..21ac334770 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-set-of-radio-buttons.spanish.md @@ -0,0 +1,93 @@ +--- +id: bad87fee1348bd9aedf08834 +title: Create a Set of Radio Buttons +localeTitle: Crear un conjunto de botones de radio +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede usar radio buttons para preguntas en las que desea que el usuario solo le dé una respuesta entre múltiples opciones. +botones de radio son un tipo de input . +Cada uno de sus botones de radio puede estar anidado dentro de su propio elemento de label . Al envolver un elemento de input dentro de un elemento de label , asociará automáticamente la entrada del botón de opción con el elemento de etiqueta que lo rodea. +Todos los botones de opción relacionados deben tener el mismo atributo de name para crear un grupo de botones de opción. Al crear un grupo de radio, la selección de cualquier botón de radio deseleccionará automáticamente los otros botones dentro del mismo grupo, lo que garantiza que el usuario solo proporcione una respuesta. +Aquí hay un ejemplo de un botón de radio: +
<label>
  <input type="radio" name="indoor-outdoor">Indoor
</label>
+Se considera una buena práctica establecer un atributo for en el elemento de label , con un valor que coincida con el valor del atributo id del elemento de input . Esto permite que las tecnologías de asistencia creen una relación vinculada entre la etiqueta y el elemento de input secundario. Por ejemplo: +
<label for="indoor">
  <input id="indoor" type="radio" name="indoor-outdoor">Indoor
</label>
+
+ +## Instructions +
+Agregue un par de botones de opción a su formulario, cada uno anidado en su propio elemento de etiqueta. Uno debe tener la opción de indoor y la otra debe tener la opción de outdoor . Ambos deben compartir el atributo de name de indoor-outdoor para crear un grupo de radio. +
+ +## Tests +
+ +```yml +tests: + - text: Tu página debe tener dos elementos de botón de radio. + testString: 'assert($("input[type="radio"]").length > 1, "Your page should have two radio button elements.");' + - text: Ponga a sus botones de radio el atributo name de indoor-outdoor . + testString: 'assert($("label > input[type="radio"]").filter("[name="indoor-outdoor"]").length > 1, "Give your radio buttons the name attribute of indoor-outdoor.");' + - text: Cada uno de sus dos elementos de botón de opción debe estar anidado en su propio elemento label . + testString: 'assert($("label > input[type="radio"]:only-child").length > 1, "Each of your two radio button elements should be nested in its own label element.");' + - text: Asegúrese de que cada uno de sus elementos label tenga una etiqueta de cierre. + testString: 'assert((code.match(/<\/label>/g) && code.match(/
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-text-field.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-text-field.spanish.md new file mode 100644 index 0000000000..22c615bc40 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-a-text-field.spanish.md @@ -0,0 +1,76 @@ +--- +id: bad87fee1348bd9aedf08829 +title: Create a Text Field +localeTitle: Crear un campo de texto +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Ahora vamos a crear un formulario web. +Los elementos de entrada son una forma conveniente de obtener información de su usuario. +Puede crear una entrada de texto como esta: +<input type="text"> +Tenga en cuenta que input elementos de input se cierran automáticamente. +
+ +## Instructions +
+Crea un elemento de input de text de tipo debajo de tus listas. +
+ +## Tests +
+ +```yml +tests: + - text: Su aplicación debe tener un elemento de input de text de tipo. + testString: 'assert($("input[type=text]").length > 0, "Your app should have an input element of type text.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+ + +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-an-ordered-list.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-an-ordered-list.spanish.md new file mode 100644 index 0000000000..85f548ff5f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/create-an-ordered-list.spanish.md @@ -0,0 +1,86 @@ +--- +id: bad87fee1348bd9aedf08828 +title: Create an Ordered List +localeTitle: Crear una lista ordenada +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML tiene otro elemento especial para crear ordered lists o listas numeradas. +listas ordenadas comienzan con un elemento <ol> apertura, seguido de cualquier número de elementos <li> . Finalmente, las listas ordenadas se cierran con un </ol> +Por ejemplo: +
<ol>
  <li>Garfield</li>
  <li>Sylvester</li>
</ol>
+crearía una lista numerada de "Garfield" y "Sylvester". +
+ +## Instructions +
+Crea una lista ordenada de las 3 cosas principales que los gatos odian más. +
+ +## Tests +
+ +```yml +tests: + - text: 'Debería tener una lista ordenada para "3 cosas que odian los gatos:"' + testString: 'assert((/Top 3 things cats hate:/i).test($("ol").prev().text()), "You should have an ordered list for "Top 3 things cats hate:"");' + - text: Deberías tener una lista desordenada para "Cosas que los gatos aman:" + testString: 'assert((/Things cats love:/i).test($("ul").prev().text()), "You should have an unordered list for "Things cats love:"");' + - text: Debes tener solo un elemento ul . + testString: 'assert.equal($("ul").length, 1, "You should have only one ul element.");' + - text: Debería tener solo un elemento ol . + testString: 'assert.equal($("ol").length, 1, "You should have only one ol element.");' + - text: Debería tener tres elementos li dentro de su elemento ul . + testString: 'assert.equal($("ul li").length, 3, "You should have three li elements within your ul element.");' + - text: Debería tener tres elementos li dentro de su elemento ol . + testString: 'assert.equal($("ol li").length, 3, "You should have three li elements within your ol element.");' + - text: Asegúrese de que su elemento ul tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/ul>/g) && code.match(/<\/ul>/g).length === code.match(/
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+ +
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/declare-the-doctype-of-an-html-document.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/declare-the-doctype-of-an-html-document.spanish.md new file mode 100644 index 0000000000..2843425d28 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/declare-the-doctype-of-an-html-document.spanish.md @@ -0,0 +1,62 @@ +--- +id: 587d78aa367417b2b2512aed +title: Declare the Doctype of an HTML Document +localeTitle: Declarar el doctype de un documento HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los desafíos hasta ahora han cubierto elementos HTML específicos y sus usos. Sin embargo, hay algunos elementos que le dan una estructura general a su página y deberían incluirse en cada documento HTML. +En la parte superior de su documento, debe indicar al navegador qué versión de HTML está usando su página. HTML es un lenguaje en evolución, y se actualiza regularmente. La mayoría de los principales navegadores son compatibles con la última especificación, que es HTML5. Sin embargo, las páginas web más antiguas pueden usar versiones anteriores del idioma. +Usted le dice al navegador esta información agregando la etiqueta <!DOCTYPE ...> en la primera línea, donde la parte " ... " es la versión de HTML. Para HTML5, utiliza <!DOCTYPE html> . +El ! y el DOCTYPE mayúsculas es importante, especialmente para los navegadores más antiguos. El html no distingue entre mayúsculas y minúsculas. +A continuación, el resto de su código HTML debe estar envuelto en etiquetas html . La apertura <html> va directamente debajo de la línea <!DOCTYPE html> , y el cierre </html> va al final de la página. +Aquí hay un ejemplo de la estructura de la página: +
<!DOCTYPE html>
<html>
  <!-- Your HTML code goes here -->
</html>
+
+ +## Instructions +
+Agregue una etiqueta DOCTYPE para HTML5 en la parte superior del documento HTML en blanco en el editor de código. Debajo de él, agregue etiquetas html apertura y cierre, que envuelven un elemento h1 . El encabezado puede incluir cualquier texto. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe incluir una etiqueta <!DOCTYPE html> . + testString: 'assert(code.match(//gi), "Your code should include a <!DOCTYPE html> tag.");' + - text: Debe haber un elemento html . + testString: 'assert($("html").length == 1, "There should be one html element.");' + - text: Las etiquetas html deben envolver alrededor de un elemento h1 . + testString: 'assert(code.match(/\s*?

\s*?.*?\s*?<\/h1>\s*?<\/html>/gi), "The html tags should wrap around one h1 element.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html + +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/define-the-head-and-body-of-an-html-document.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/define-the-head-and-body-of-an-html-document.spanish.md new file mode 100644 index 0000000000..b4a4e26ea1 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/define-the-head-and-body-of-an-html-document.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d78aa367417b2b2512aec +title: Define the Head and Body of an HTML Document +localeTitle: Definir la cabeza y el cuerpo de un documento HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede agregar otro nivel de organización en su documento HTML dentro de las etiquetas html con los elementos de head y body . Cualquier marca con información sobre su página irá a la etiqueta de head . Luego, cualquier marca con el contenido de la página (lo que se muestra para un usuario) entraría en la etiqueta del body . +Los elementos de metadatos, como link , meta , title y style , por lo general van dentro de la head del elemento. +Aquí hay un ejemplo del diseño de una página: +
<!DOCTYPE html>
<html>
  <head>
    <!-- metadata elements -->
  </head>
  <body>
    <!-- page contents -->
  </body>
</html>
+
+ +## Instructions +
+Edita el marcado para que haya una head y un body . La head elemento sólo debe incluir el title , y el body elemento sólo debe incluir la h1 y p . +
+ +## Tests +
+ +```yml +tests: + - text: Solo debe haber un elemento de head en la página. + testString: 'assert($("head").length == 1, "There should be only one head element on the page.");' + - text: Solo debe haber un elemento de body en la página. + testString: 'assert($("body").length == 1, "There should be only one body element on the page.");' + - text: La head elemento debe ser un hijo de la html elemento. + testString: 'assert($("html").children("head").length == 1, "The head element should be a child of the html element.");' + - text: El elemento del body debe ser un elemento secundario del elemento html . + testString: 'assert($("html").children("body").length == 1, "The body element should be a child of the html element.");' + - text: La head elemento debe envolver el title del elemento. + testString: 'assert(code.match(/\s*?\s*?.*?\s*?<\/title>\s*?<\/head>/gi), "The <code>head</code> element should wrap around the <code>title</code> element.");' + - text: El elemento del <code>body</code> debe envolver alrededor de los elementos <code>h1</code> y <code>p</code> . + testString: 'assert($("body").children("h1").length == 1 && $("body").children("p").length == 1, "The <code>body</code> element should wrap around both the <code>h1</code> and <code>p</code> elements.");' + +``` + +</section> + +## Challenge Seed +<section id='challengeSeed'> + +<div id='html-seed'> + +```html +<!DOCTYPE html> +<html> + <title>The best page ever + +

The best page ever

+

Cat ipsum dolor sit amet, jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed. Go into a room to decide you didn't want to be in there anyway. I like big cats and i can not lie kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Meow i could pee on this if i had the energy for slap owner's face at 5am until human fills food dish yet scamper. Knock dish off table head butt cant eat out of my own dish scratch the furniture. Make meme, make cute face. Sleep in the bathroom sink chase laser but pee in the shoe. Paw at your fat belly licks your face and eat grass, throw it back up kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+ + +``` + + + + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/delete-html-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/delete-html-elements.spanish.md new file mode 100644 index 0000000000..db76b2c58b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/delete-html-elements.spanish.md @@ -0,0 +1,63 @@ +--- +id: bad87fed1348bd9aedf08833 +title: Delete HTML Elements +localeTitle: Eliminar elementos HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Nuestro teléfono no tiene mucho espacio vertical. +Eliminemos los elementos innecesarios para que podamos comenzar a construir nuestra CatPhotoApp. +
+ +## Instructions +
+Borre su elemento h1 para que podamos simplificar nuestra vista. +
+ +## Tests +
+ +```yml +tests: + - text: Eliminar su elemento h1 . + testString: 'assert(!code.match(/

/gi) && !code.match(/<\/h1>/gi), "Delete your h1 element.");' + - text: Deja tu elemento h2 en la página. + testString: 'assert(code.match(/

[\w\W]*<\/h2>/gi), "Leave your h2 element on the page.");' + - text: Deja tu elemento p en la página. + testString: 'assert(code.match(/

[\w\W]*<\/p>/gi), "Leave your p element on the page.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html +

Hello World

+ +

CatPhotoApp

+ +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "

CatPhotoApp

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/fill-in-the-blank-with-placeholder-text.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/fill-in-the-blank-with-placeholder-text.spanish.md new file mode 100644 index 0000000000..c827a648db --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/fill-in-the-blank-with-placeholder-text.spanish.md @@ -0,0 +1,58 @@ +--- +id: bad87fee1348bd9aedf08833 +title: Fill in the Blank with Placeholder Text +localeTitle: Rellene el espacio en blanco con el texto del marcador de posición +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los desarrolladores web tradicionalmente usan el lorem ipsum text como texto de marcador de posición. El texto 'lorem ipsum' se raspa al azar de un famoso pasaje de Cicerón de la Antigua Roma. +El texto de Lorem ipsum ha sido utilizado como texto de marcador de posición por tipógrafos desde el siglo XVI, y esta tradición continúa en la web. +Bueno, 5 siglos es lo suficientemente largo. Ya que estamos construyendo un CatPhotoApp, usemos algo que se llama kitty ipsum text . +
+ +## Instructions +
+Reemplace el texto dentro de su elemento p con las primeras palabras de este texto de kitty ipsum: Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento p debe contener las primeras palabras del kitty ipsum text proporcionado. + testString: 'assert.isTrue((/Kitty(\s)+ipsum/gi).test($("p").text()), "Your p element should contain the first few words of the provided kitty ipsum text.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

Hello World

+ +

CatPhotoApp

+ +

Hello Paragraph

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.spanish.md new file mode 100644 index 0000000000..b925570604 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/headline-with-the-h2-element.spanish.md @@ -0,0 +1,60 @@ +--- +id: bad87fee1348bd9aedf0887a +title: Headline with the h2 Element +localeTitle: Titular con el elemento h2 +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En las próximas lecciones, construiremos una aplicación web de fotos de gatos HTML5 pieza por pieza. +El elemento h2 que agregará en este paso agregará un encabezado de nivel dos a la página web. +Este elemento le dice al navegador acerca de la estructura de su sitio web. h1 elementos h1 se usan a menudo para los encabezados principales, mientras que los elementos h2 se usan generalmente para los subtítulos. También hay elementos h3 , h4 , h5 y h6 para indicar diferentes niveles de subtítulos. +
+ +## Instructions +
+Agregue una etiqueta h2 que diga "CatPhotoApp" para crear un segundo element HTML debajo de su elemento h1 "Hello World". +
+ +## Tests +
+ +```yml +tests: + - text: Crear un elemento h2 . + testString: 'assert(($("h2").length > 0), "Create an h2 element.");' + - text: Asegúrese de que su elemento h2 tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/h2>/g) && code.match(/<\/h2>/g).length === code.match(/

/g).length, "Make sure your h2 element has a closing tag.");' + - text: Su elemento h2 debe tener el texto "CatPhotoApp". + testString: 'assert.isTrue((/cat(\s)?photo(\s)?app/gi).test($("h2").text()), "Your h2 element should have the text "CatPhotoApp".");' + - text: Su elemento h1 debe tener el texto "Hola mundo". + testString: 'assert.isTrue((/hello(\s)+world/gi).test($("h1").text()), "Your h1 element should have the text "Hello World".");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html +

Hello World

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element.spanish.md new file mode 100644 index 0000000000..333700bf8c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/inform-with-the-paragraph-element.spanish.md @@ -0,0 +1,60 @@ +--- +id: bad87fee1348bd9aedf08801 +title: Inform with the Paragraph Element +localeTitle: Informar con el elemento de párrafo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+elementos +p son el elemento preferido para el texto de párrafo en sitios web. p es la abreviatura de "párrafo". +Puedes crear un elemento de párrafo como este: +<p>I'm ap tag!</p> +
+ +## Instructions +
+Crea un elemento p debajo de tu elemento h2 y dale el texto "Hola párrafo". +
+ +## Tests +
+ +```yml +tests: + - text: Crea un elemento p . + testString: 'assert(($("p").length > 0), "Create a p element.");' + - text: Su elemento p debe tener el texto "Hola párrafo". + testString: 'assert.isTrue((/hello(\s)+paragraph/gi).test($("p").text()), "Your p element should have the text "Hello Paragraph".");' + - text: Asegúrese de que su elemento p tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/

p element has a closing tag.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html +

Hello World

+

CatPhotoApp

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.spanish.md new file mode 100644 index 0000000000..5f93d64bd8 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/introduction-to-html5-elements.spanish.md @@ -0,0 +1,70 @@ +--- +id: bad87fee1348bd9aecf08801 +title: Introduction to HTML5 Elements +localeTitle: Introducción a los elementos HTML5 +challengeType: 0 +videoUrl: '' +--- + +## Description +
+HTML5 introduce etiquetas HTML más descriptivas. Estos incluyen header , footer , nav , video , article , section y otros. +Estas etiquetas hacen que su HTML sea más fácil de leer, y también ayudan con la optimización del motor de búsqueda (SEO) y la accesibilidad. +La etiqueta HTML5 main ayuda a los motores de búsqueda y otros desarrolladores a encontrar el contenido principal de su página. +Nota
Muchas de las nuevas etiquetas HTML5 y sus beneficios se tratan en la sección de accesibilidad aplicada. +
+ +## Instructions +
+Cree un segundo elemento p después del elemento p existente con el siguiente texto de ipsum del gatito: Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. +Envuelva los párrafos con una etiqueta main apertura y cierre. +
+ +## Tests +
+ +```yml +tests: + - text: Necesitas 2 elementos p con el texto de Kitty Ipsum. + testString: 'assert($("p").length > 1, "You need 2 p elements with Kitty Ipsum text.");' + - text: Asegúrese de que cada uno de sus elementos p tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/p>/g) && code.match(/<\/p>/g).length === code.match(/

p elements has a closing tag.");' + - text: Su elemento p debe contener las primeras palabras del kitty ipsum text adicional proporcionado. + testString: 'assert.isTrue((/Purr\s+jump\s+eat/gi).test($("p").text()), "Your p element should contain the first few words of the provided additional kitty ipsum text.");' + - text: Su código debe tener un elemento main . + testString: 'assert($("main").length === 1, "Your code should have one main element.");' + - text: El elemento main debe tener dos elementos de párrafo como niños. + testString: 'assert($("main").children("p").length === 2, "The main element should have two paragraph elements as children.");' + - text: La etiqueta main apertura debe aparecer antes de la etiqueta del primer párrafo. + testString: 'assert(code.match(/

\s*?

/g), "The opening main tag should come before the first paragraph tag.");' + - text: La etiqueta main cierre debe aparecer después de la segunda etiqueta de párrafo de cierre. + testString: 'assert(code.match(/<\/p>\s*?<\/main>/g), "The closing main tag should come after the second closing paragraph tag.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+ +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.spanish.md new file mode 100644 index 0000000000..48d03d0473 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-external-pages-with-anchor-elements.spanish.md @@ -0,0 +1,69 @@ +--- +id: bad87fee1348bd9aedf08816 +title: Link to External Pages with Anchor Elements +localeTitle: Enlace a páginas externas con elementos de anclaje +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede usar elementos de anchor para vincular contenido fuera de su página web. +elementos de anchor +necesitan una dirección web de destino denominada atributo href . También necesitan texto de anclaje. Aquí hay un ejemplo: +<a href="https://freecodecamp.org">this links to freecodecamp.org</a> +Entonces su navegador mostrará el texto "esto enlaza a freecodecamp.org" como un enlace que puede hacer clic. Y ese enlace lo llevará a la dirección web https://spanish.freecodecamp.org . +
+ +## Instructions +
+Crear una a elemento que une a http://freecatphotoapp.com y tiene "fotos del gato" como su anchor text . +
+ +## Tests +
+ +```yml +tests: + - text: Su a elemento debe tener el anchor text de fotos "gato". + testString: 'assert((/cat photos/gi).test($("a").text()), "Your a element should have the anchor text of "cat photos".");' + - text: 'Es necesario un a elemento que une a http://freecatphotoapp .com ' + testString: 'assert(/http:\/\/(www\.)?freecatphotoapp\.com/gi.test($("a").attr("href")), "You need an a element that links to http://freecatphotoapp.com");' + - text: Asegúrese de que su a elemento tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/a>/g) && code.match(/<\/a>/g).length === code.match(/a element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+ + + + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-internal-sections-of-a-page-with-anchor-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-internal-sections-of-a-page-with-anchor-elements.spanish.md new file mode 100644 index 0000000000..5b37b61ece --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/link-to-internal-sections-of-a-page-with-anchor-elements.spanish.md @@ -0,0 +1,82 @@ +--- +id: bad88fee1348bd9aedf08816 +title: Link to Internal Sections of a Page with Anchor Elements +localeTitle: Enlace a las secciones internas de una página con elementos de anclaje +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los elementos de anclaje también se pueden usar para crear enlaces internos para saltar a diferentes secciones dentro de una página web. +Para crear un enlace interno, asigna el atributo href un enlace a un símbolo de hash # más el valor del atributo id para el elemento al que desea enlazar internamente, generalmente más abajo en la página. A continuación, deberá agregar el mismo atributo de id al elemento al que se está vinculando. Un id es un atributo que describe de forma única un elemento. +A continuación se muestra un ejemplo de un enlace de anclaje interno y su elemento de destino: +
<a href="#contacts-header">Contacts</a>
...
<h2 id="contacts-header">Contacts</h2>
+Cuando los usuarios hacen clic en el enlace de Contactos, serán llevados a la sección de la página web con el elemento del encabezado de Contactos . +
+ +## Instructions +
+Cambie su enlace externo a un enlace interno cambiando el atributo href a "# footer" y el texto de "fotos del gato" a "Saltar a la parte inferior". +Elimine el atributo target="_blank" de la etiqueta de anclaje ya que esto hace que el documento vinculado se abra en una nueva pestaña de ventana. +Luego agregue un atributo id con un valor de "pie de página" al elemento <footer> en la parte inferior de la página. +
+ +## Tests +
+ +```yml +tests: + - text: Solo debe haber una etiqueta de anclaje en su página. + testString: 'assert($("a").length == 1, "There should be only one anchor tag on your page.");' + - text: Debe haber solo una etiqueta footer en su página. + testString: 'assert($("footer").length == 1, "There should be only one footer tag on your page.");' + - text: 'La etiqueta a debe tener un atributo href establecido en "#footer".' + testString: 'assert($("a").eq(0).attr("href") == "#footer", "The a tag should have an href attribute set to "#footer".");' + - text: La etiqueta a no debe tener el atributo target + testString: 'assert(typeof $("a").eq(0).attr("target") == typeof undefined || $("a").eq(0).attr("target") == true, "The a tag should not have a target attribute");' + - text: El un texto debe ser "Jump to Bottom". + testString: 'assert($("a").eq(0).text().match(/Jump to Bottom/gi), "The a text should be "Jump to Bottom".");' + - text: La etiqueta footer debe tener un atributo id establecido en "footer". + testString: 'assert($("footer").eq(0).attr("id") == "footer", "The footer tag should have an id attribute set to "footer".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+ + cat photos + + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched. Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff. Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+

Meowwww loved it, hated it, loved it, hated it yet spill litter box, scratch at owner, destroy all furniture, especially couch or lay on arms while you're using the keyboard. Missing until dinner time toy mouse squeak roll over. With tail in the air lounge in doorway. Man running from cops stops to pet cats, goes to jail.

+

Intently stare at the same spot poop in the plant pot but kitten is playing with dead mouse. Get video posted to internet for chasing red dot leave fur on owners clothes meow to be let out and mesmerizing birds leave fur on owners clothes or favor packaging over toy so purr for no reason. Meow to be let out play time intently sniff hand run outside as soon as door open yet destroy couch.

+ +
+ +
Copyright Cat Photo App
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/make-dead-links-using-the-hash-symbol.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/make-dead-links-using-the-hash-symbol.spanish.md new file mode 100644 index 0000000000..b1f24f6694 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/make-dead-links-using-the-hash-symbol.spanish.md @@ -0,0 +1,62 @@ +--- +id: bad87fee1348bd9aedf08817 +title: Make Dead Links Using the Hash Symbol +localeTitle: Haz enlaces muertos usando el símbolo de hash +challengeType: 0 +videoUrl: '' +--- + +## Description +
+veces que desea agregar a los elementos a su sitio web antes de saber donde van a unir. +Esto también es útil cuando está cambiando el comportamiento de un enlace usando JavaScript , que conoceremos más adelante. +
+ +## Instructions +
+El valor actual del atributo href es un enlace que apunta a "http://freecatphotoapp.com". Reemplace el valor del atributo href con un # , también conocido como símbolo de hash, para crear un enlace muerto. +Por ejemplo: href="#" +
+ +## Tests +
+ +```yml +tests: + - text: 'Su a elemento debe ser un vínculo roto con el valor de la href atributo establecido en '#'.' + testString: 'assert($("a").attr("href") === "#", "Your a element should be a dead link with the value of the href attribute set to "#".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.spanish.md new file mode 100644 index 0000000000..f90e691e42 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.spanish.md @@ -0,0 +1,83 @@ +--- +id: bad87fee1348bd9aede08817 +title: Nest an Anchor Element within a Paragraph +localeTitle: Anidar un elemento de anclaje dentro de un párrafo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede anidar enlaces dentro de otros elementos de texto. +
<p>
Here's a <a target="_blank" href="http://freecodecamp.org"> link to freecodecamp.org</a> for you to follow.
</p>
+Desglosemos el ejemplo: +El texto normal se ajusta en el elemento p :
<p> Here's a ... for you to follow. </p> +siguiente es el elemento de anchor <a> (que requiere una etiqueta de cierre </a> ):
<a> ... </a> +target es un atributo de etiqueta de anclaje que especifica dónde abrir el enlace y el valor "_blank" especifica que se abra el enlace en una nueva pestaña +href es un atributo de etiqueta de anclaje que contiene la URL Dirección del enlace:
<a href="http://freecodecamp.org"> ... </a> +El texto, "link to freecodecamp.org" , dentro del elemento de anchor text llamado anchor text , mostrará un enlace para hacer clic:
<a href=" ... ">link to freecodecamp.org</a> +La salida final del ejemplo se verá así:

Aquí hay un enlace a freecodecamp.org para que lo sigas.

+
+ +## Instructions +
+Ahora nido de su actual a elemento dentro de un nuevo p elemento (justo a continuación de la main elemento). El nuevo párrafo debe tener un texto que diga "Ver más fotos de gatos", donde "fotos de gatos" es un enlace, y el resto del texto es texto sin formato. +
+ +## Tests +
+ +```yml +tests: + - text: 'Es necesario un a elemento que une a 'http://freecatphotoapp.com'.' + testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").length > 0 || $("a[href=\"http://www.freecatphotoapp.com\"]").length > 0), "You need an a element that links to "http://freecatphotoapp.com".");' + - text: Su a elemento debe tener el texto de anclaje de fotos "gato" + testString: 'assert($("a").text().match(/cat\sphotos/gi), "Your a element should have the anchor text of "cat photos"");' + - text: Crear un nuevo p elemento alrededor de su a elemento. Debe haber al menos 3 etiquetas p en total en su código HTML. + testString: 'assert($("p") && $("p").length > 2, "Create a new p element around your a element. There should be at least 3 total p tags in your HTML code.");' + - text: Su a elemento debe estar anidada dentro de su nueva p elemento. + testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().is("p") || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().is("p")), "Your a element should be nested within your new p element.");' + - text: Su elemento p debe tener el texto "Ver más" (con un espacio detrás de él). + testString: 'assert(($("a[href=\"http://freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi) || $("a[href=\"http://www.freecatphotoapp.com\"]").parent().text().match(/View\smore\s/gi)), "Your p element should have the text "View more " (with a space after it).");' + - text: Su a elemento no debería tener el texto "Ver más". + testString: 'assert(!$("a").text().match(/View\smore/gi), "Your a element should not have the text "View more".");' + - text: Asegúrese de que cada uno de sus elementos p tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/p>/g) && code.match(/

/g).length === code.match(/

p elements has a closing tag.");' + - text: Asegúrese de que cada uno de sus a elementos tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/a>/g) && code.match(//g).length === code.match(/a elements has a closing tag.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+ + cat photos + + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-many-elements-within-a-single-div-element.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-many-elements-within-a-single-div-element.spanish.md new file mode 100644 index 0000000000..a768d8479b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/nest-many-elements-within-a-single-div-element.spanish.md @@ -0,0 +1,89 @@ +--- +id: bad87fee1348bd9aede08835 +title: Nest Many Elements within a Single div Element +localeTitle: Anidar muchos elementos dentro de un único elemento div +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El elemento div , también conocido como elemento de división, es un contenedor de propósito general para otros elementos. +El elemento div es probablemente el elemento HTML más utilizado de todos. +Al igual que cualquier otro elemento que no se cierre automáticamente, puede abrir un elemento div con <div> y cerrarlo en otra línea con </div> . +
+ +## Instructions +
+Anide sus listas de "Cosas que los gatos aman" y "Cosas que los gatos odian", todo dentro de un único elemento div . +Sugerencia: intente colocar su etiqueta div apertura sobre el elemento p "Things cats love" y su etiqueta div cierre después de su etiqueta ol cierre para que ambas listas estén dentro de una div . +
+ +## Tests +
+ +```yml +tests: + - text: Anida tus elementos p dentro de tu elemento div . + testString: 'assert($("div").children("p").length > 1, "Nest your p elements inside your div element.");' + - text: Anida tu elemento ul dentro de tu elemento div . + testString: 'assert($("div").children("ul").length > 0, "Nest your ul element inside your div element.");' + - text: Anida tu elemento ol dentro de tu elemento div . + testString: 'assert($("div").children("ol").length > 0, "Nest your ol element inside your div element.");' + - text: Asegúrese de que su elemento div tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/<\/div>/g).length === code.match(/
/g).length, "Make sure your div element has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+ +
+ +
+ + +
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/say-hello-to-html-elements.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/say-hello-to-html-elements.spanish.md new file mode 100644 index 0000000000..cf8cb36c83 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/say-hello-to-html-elements.spanish.md @@ -0,0 +1,61 @@ +--- +id: bd7123c8c441eddfaeb5bdef +title: Say Hello to HTML Elements +localeTitle: Diga hola a los elementos HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Bienvenido a los desafíos de codificación HTML de freeCodeCamp. Estos te guiarán paso a paso a través del desarrollo web. +Primero, comenzarás construyendo una página web simple usando HTML. Puede editar el code en su code editor , que está incrustado en esta página web. +¿Ve el código en su editor de código que dice <h1>Hello</h1> ? Eso es un element HTML. +La mayoría de los elementos HTML tienen una opening tag y una closing tag . +Las etiquetas de apertura tienen este aspecto: +<h1> +etiquetas de cierre tienen este aspecto: +</h1> +La única diferencia entre las etiquetas de apertura y cierre es la barra diagonal posterior al soporte de apertura de una etiqueta de cierre. +Cada desafío tiene pruebas que puede ejecutar en cualquier momento haciendo clic en el botón "Ejecutar pruebas". Cuando pase todas las pruebas, se le solicitará que envíe su solución y pase al siguiente desafío de codificación. +
+ +## Instructions +
+Para pasar la prueba en este desafío, cambie el texto de su elemento h1 para que diga "Hola mundo". +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento h1 debe tener el texto "Hola mundo". + testString: 'assert.isTrue((/hello(\s)+world/gi).test($("h1").text()), "Your h1 element should have the text "Hello World".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

Hello

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/turn-an-image-into-a-link.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/turn-an-image-into-a-link.spanish.md new file mode 100644 index 0000000000..a0c8b48ef3 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/turn-an-image-into-a-link.spanish.md @@ -0,0 +1,68 @@ +--- +id: bad87fee1348bd9aedf08820 +title: Turn an Image into a Link +localeTitle: Convertir una imagen en un enlace +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Se puede hacer elementos en enlaces anidando dentro de un a elemento. +Nido de su imagen dentro de un a elemento. Aquí hay un ejemplo: +<a href="#"><img src="https://bit.ly/fcc-running-cats" alt="Three kittens running towards the camera."></a> +Recuerda usar # como la propiedad href a elemento para convertirlo en un enlace muerto. +
+ +## Instructions +
+Coloque el elemento de imagen existente dentro de un elemento de anclaje. +Una vez que hayas hecho esto, desplázate sobre tu imagen con el cursor. El puntero normal de su cursor debe convertirse en el enlace que hace clic en el puntero. La foto es ahora un enlace. +
+ +## Tests +
+ +```yml +tests: + - text: Nido el vigente img elemento dentro de un a elemento. + testString: 'assert($("a").children("img").length > 0, "Nest the existing img element within an a element.");' + - text: 'Su a elemento debe ser un vínculo roto con un href atributo establecido en # .' + testString: 'assert(new RegExp("#").test($("a").children("img").parent().attr("href")), "Your a element should be a dead link with a href attribute set to #.");' + - text: Asegúrese de que cada uno de sus a elementos tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/a>/g) && code.match(//g).length === code.match(/a elements has a closing tag.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Kitty ipsum dolor sit amet, shed everywhere shed everywhere stretching attack your ankles chase the red dot, hairball run catnip eat the grass sniff.

+

Purr jump eat the grass rip the couch scratched sunbathe, shed everywhere rip the couch sleep in the sink fluffy fur catnip scratched.

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/uncomment-html.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/uncomment-html.spanish.md new file mode 100644 index 0000000000..25883d997c --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/uncomment-html.spanish.md @@ -0,0 +1,66 @@ +--- +id: bad87fee1348bd9aedf08802 +title: Uncomment HTML +localeTitle: Descomentar HTML +challengeType: 0 +videoUrl: '' +--- + +## Description +
+comentarios son una forma en la que puede dejar comentarios para otros desarrolladores dentro de su código sin afectar el resultado resultante que se muestra al usuario final. +comentarios también son una forma conveniente de desactivar el código sin tener que eliminarlo por completo. +comentarios en HTML comienzan con <!-- , y terminan con un --> +
+ +## Instructions +
+Descomenta tus elementos h1 , h2 p . +
+ +## Tests +
+ +```yml +tests: + - text: Haga que su elemento h1 visible en su página sin comentarlo. + testString: 'assert($("h1").length > 0, "Make your h1 element visible on your page by uncommenting it.");' + - text: Haga que su elemento h2 visible en su página sin comentarlo. + testString: 'assert($("h2").length > 0, "Make your h2 element visible on your page by uncommenting it.");' + - text: Haz que tu elemento p visible en tu página descomprimiéndolo. + testString: 'assert($("p").length > 0, "Make your p element visible on your page by uncommenting it.");' + - text: 'Asegúrese de eliminar todas las etiquetas de comentarios finales, es decir, --> .' + testString: 'assert(!/[^fc]-->/gi.test(code.replace(/ * +``` + + + + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/use-html5-to-require-a-field.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/use-html5-to-require-a-field.spanish.md new file mode 100644 index 0000000000..2e46ef8eed --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/use-html5-to-require-a-field.spanish.md @@ -0,0 +1,76 @@ +--- +id: bad87fee1348bd9aedc08830 +title: Use HTML5 to Require a Field +localeTitle: Usa HTML5 para requerir un campo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede requerir campos de formulario específicos para que su usuario no pueda enviar su formulario hasta que él o ella los haya completado. +Por ejemplo, si desea hacer que un campo de entrada de texto sea obligatorio, simplemente puede agregar el atributo required dentro de su elemento de input , de esta manera: <input type="text" required> +
+ +## Instructions +
+Haga que su input texto sea un campo required , para que su usuario no pueda enviar el formulario sin completar este campo. +Luego intente enviar el formulario sin ingresar ningún texto. ¿Ves cómo tu formulario HTML5 te notifica que el campo es obligatorio? +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento de input texto debe tener el atributo required . + testString: 'assert($("input").prop("required"), "Your text input element should have the required attribute.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html +

CatPhotoApp

+
+

Click here to view more cat photos.

+ + A cute orange cat lying on its back. + +

Things cats love:

+
    +
  • cat nip
  • +
  • laser pointers
  • +
  • lasagna
  • +
+

Top 3 things cats hate:

+
    +
  1. flea treatment
  2. +
  3. thunder
  4. +
  5. other cats
  6. +
+
+ + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/add-flex-superpowers-to-the-tweet-embed.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/add-flex-superpowers-to-the-tweet-embed.spanish.md new file mode 100644 index 0000000000..3ff07b5c28 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/add-flex-superpowers-to-the-tweet-embed.spanish.md @@ -0,0 +1,153 @@ +--- +id: 587d78ab367417b2b2512af1 +title: Add Flex Superpowers to the Tweet Embed +localeTitle: Añadir Flex Superpowers al Tweet Insertar +challengeType: 0 +videoUrl: '' +--- + +## Description +
+A la derecha está la inserción de tweets que se utilizará como ejemplo práctico. Algunos de los elementos se verían mejor con un diseño diferente. El último desafío demostró display: flex . Aquí lo agregará a varios componentes en la inserción de tweets para comenzar a ajustar su posicionamiento. +
+ +## Instructions +
+Agregue la display: flex propiedades CSS display: flex a todos los elementos siguientes: tenga en cuenta que los selectores ya están configurados en el header CSS: +, el .profile-name de .follow-btn del encabezado, .follow-btn del encabezado, h3 y h4 del encabezado el footer , y los .stats de pie de .stats . +
+ +## Tests +
+ +```yml +tests: + - text: Su header debe tener una propiedad de display configurada para flexionar. + testString: 'assert($("header").css("display") == "flex", "Your header should have a display property set to flex.");' + - text: Su footer debe tener una propiedad de display configurada para flexionar. + testString: 'assert($("footer").css("display") == "flex", "Your footer should have a display property set to flex.");' + - text: Tu h3 debería tener una propiedad de display configurada para flexionar. + testString: 'assert($("h3").css("display") == "flex", "Your h3 should have a display property set to flex.");' + - text: Tu h4 debería tener una propiedad de display configurada para flexionar. + testString: 'assert($("h4").css("display") == "flex", "Your h4 should have a display property set to flex.");' + - text: Su .profile-name debe tener una propiedad de display configurada para flexionar. + testString: 'assert($(".profile-name").css("display") == "flex", "Your .profile-name should have a display property set to flex.");' + - text: Su .follow-btn debe tener una propiedad de display configurada para flexionar. + testString: 'assert($(".follow-btn").css("display") == "flex", "Your .follow-btn should have a display property set to flex.");' + - text: Sus .stats deben tener una propiedad de display configurada para flexionar. + testString: 'assert($(".stats").css("display") == "flex", "Your .stats should have a display property set to flex.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+ +
+
+

I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.

+ 1:32 PM - 12 Jan 2018 +
+
+
+
+
+ 107 Retweets +
+ +
+
+ + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-align-items-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-align-items-property.spanish.md new file mode 100644 index 0000000000..6baad054e8 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-align-items-property.spanish.md @@ -0,0 +1,80 @@ +--- +id: 587d78ad367417b2b2512af8 +title: Align Elements Using the align-items Property +localeTitle: Alinear elementos usando la propiedad align-items +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad align-items es similar a justify-content . Recuerde que la propiedad justify justify-content alineaba elementos flexibles a lo largo del eje principal. Para las filas, el eje principal es una línea horizontal y para las columnas es una línea vertical. +Los contenedores Flex también tienen un eje transversal que es el opuesto al eje principal. Para las filas, el eje transversal es vertical y para las columnas, el eje transversal es horizontal. +CSS ofrece la propiedad align-items para alinear elementos flexibles a lo largo del eje transversal. Para una fila, le dice a CSS cómo empujar los elementos en toda la fila hacia arriba o hacia abajo dentro del contenedor. Y para una columna, cómo empujar todos los elementos a la izquierda o derecha dentro del contenedor. +Los diferentes valores disponibles para align-items de align-items incluyen: + +
+ +## Instructions +
+Un ejemplo ayuda a mostrar esta propiedad en acción. Agregue la propiedad CSS align-items al align-items #box-container y asígnele un valor de center. +Bonus
Pruebe las otras opciones para la propiedad align-items en el editor de código para ver sus diferencias. Pero tenga en cuenta que un valor de centro es el único que pasará este desafío. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-container debería tener una propiedad align-items establecida en un valor de center.' + testString: 'assert($("#box-container").css("align-items") == "center", "The #box-container element should have an align-items property set to a value of center.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+

Hello

+

Goodbye

+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.spanish.md new file mode 100644 index 0000000000..633bfc56d5 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.spanish.md @@ -0,0 +1,80 @@ +--- +id: 587d78ac367417b2b2512af6 +title: Align Elements Using the justify-content Property +localeTitle: Alinear elementos usando la propiedad justify-content +challengeType: 0 +videoUrl: '' +--- + +## Description +
+A veces, los elementos flexibles dentro de un contenedor flexible no llenan todo el espacio en el contenedor. Es común querer decirle a CSS cómo alinear y espaciar los elementos flexibles de una determinada manera. Afortunadamente, la propiedad justify-content tiene varias opciones para hacer esto. Pero primero, hay una terminología importante que entender antes de revisar esas opciones. +Aquí hay una imagen útil que muestra una fila para ilustrar los conceptos a continuación. +Recuerde que la configuración de un contenedor flexible como una fila coloca los elementos flexibles uno al lado del otro de izquierda a derecha. Un contenedor flexible configurado como una columna coloca los elementos flexibles en una pila vertical de arriba a abajo. Para cada uno, la dirección en la que se disponen los elementos flexibles se denomina eje principal . Para una fila, esta es una línea horizontal que corta cada elemento. Y para una columna, el eje principal es una línea vertical a través de los elementos. +Hay varias opciones sobre cómo espaciar los elementos flexibles a lo largo de la línea que es el eje principal. Uno de los más utilizados es justify-content: center; , que alinea todos los elementos flexibles con el centro dentro del contenedor flexible. Otras opciones incluyen: + +
+ +## Instructions +
+Un ejemplo ayuda a mostrar esta propiedad en acción. Agregue la propiedad CSS justify-content al elemento #box-container y asígnele un valor de center. +Bonus
Pruebe las otras opciones para la propiedad justify-content en el editor de código para ver sus diferencias. Pero tenga en cuenta que un valor de centro es el único que pasará este desafío. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-container debería tener una propiedad justify-content establecida en un valor de center'. + testString: 'assert($("#box-container").css("justify-content") == "center", "The #box-container element should have a justify-content property set to a value of center.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-a-column-in-the-tweet-embed.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-a-column-in-the-tweet-embed.spanish.md new file mode 100644 index 0000000000..364067622d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-a-column-in-the-tweet-embed.spanish.md @@ -0,0 +1,139 @@ +--- +id: 587d78ac367417b2b2512af5 +title: Apply the flex-direction Property to Create a Column in the Tweet Embed +localeTitle: Aplique la propiedad de dirección flexible para crear una columna en la inserción de tweets +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El header y el footer inserción del tweet usaron la propiedad de flex-direction anteriormente con un valor de fila. De manera similar, los elementos dentro del elemento .profile-name funcionarán bien apilados como una columna. +
+ +## Instructions +
+Agregue la propiedad CSS flex-direction al elemento .profile-name del encabezado y establezca el valor en columna. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento .profile-name debe tener una propiedad de flex-direction configurada en columna. + testString: 'assert($(".profile-name").css("flex-direction") == "column", "The .profile-name element should have a flex-direction property set to column.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+ +
+
+

I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.

+ 1:32 PM - 12 Jan 2018 +
+
+
+
+
+ 107 Retweets +
+ +
+
+ + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed.spanish.md new file mode 100644 index 0000000000..6c35da898b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed.spanish.md @@ -0,0 +1,146 @@ +--- +id: 587d78ab367417b2b2512af3 +title: Apply the flex-direction Property to Create Rows in the Tweet Embed +localeTitle: Aplique la propiedad de dirección flexible para crear filas en el Tweet Insertar +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El header y el footer de footer en el ejemplo de inserción de tweets tienen elementos secundarios que se podrían organizar como filas usando la propiedad de flex-direction . Esto le dice a CSS que alinee a los niños horizontalmente. +
+ +## Instructions +
+Agregue la propiedad CSS flex-direction al header y al footer y establezca el valor en fila. +
+ +## Tests +
+ +```yml +tests: + - text: El header debe tener una propiedad de flex-direction establecida en fila. + testString: 'assert(code.match(/header\s*?{[^}]*?flex-direction:\s*?row;/g), "The header should have a flex-direction property set to row.");' + - text: El footer debe tener una propiedad de flex-direction configurada en fila. + testString: 'assert(code.match(/footer\s*?{[^}]*?flex-direction:\s*?row;/g), "The footer should have a flex-direction property set to row.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+ +
+
+

I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.

+ 1:32 PM - 12 Jan 2018 +
+
+
+
+
+ 107 Retweets +
+ +
+
+ + + +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "header {flex-direction: row;} footer {flex-direction: row;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-display-flex-to-position-two-boxes.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-display-flex-to-position-two-boxes.spanish.md new file mode 100644 index 0000000000..94f57aed71 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-display-flex-to-position-two-boxes.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d78ab367417b2b2512af0 +title: 'Use display +localeTitle: 'Usar pantalla: flex to Position Two Boxes' +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Esta sección utiliza estilos de desafío alternativos para mostrar cómo usar CSS para posicionar elementos de una manera flexible. Primero, un desafío explicará la teoría, luego un desafío práctico utilizando un componente de tweet simple aplicará el concepto flexbox. +Colocación de la display: flex; propiedades CSS display: flex; en un elemento le permite usar otras propiedades de flexión para construir una página receptiva. +
+ +## Instructions +
+Agregue la display propiedades CSS a #box-container y establezca su valor en flex. +
+ +## Tests +
+ +```yml +tests: + - text: ' #box-container debería tener la propiedad de display establecida en un valor de flex'. + testString: 'assert($("#box-container").css("display") == "flex", "#box-container should have the display property set to a value of flex.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-items-property-in-the-tweet-embed.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-items-property-in-the-tweet-embed.spanish.md new file mode 100644 index 0000000000..a713a64fe8 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-items-property-in-the-tweet-embed.spanish.md @@ -0,0 +1,142 @@ +--- +id: 587d78ad367417b2b2512af9 +title: Use the align-items Property in the Tweet Embed +localeTitle: Use la propiedad align-items en el Tweet Insertar +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El último desafío introdujo la propiedad align-items y dio un ejemplo. Esta propiedad se puede aplicar a algunos elementos de inserción de tweets para alinear los elementos flexibles dentro de ellos. +
+ +## Instructions +
+Agregue la propiedad CSS align-items al align-items .follow-btn del encabezado. Establezca el valor en el centro. +
+ +## Tests +
+ +```yml +tests: + - text: El elemento .follow-btn debe tener la propiedad align-items establecida en un valor de center. + testString: 'assert($(".follow-btn").css("align-items") == "center", "The .follow-btn element should have the align-items property set to a value of center.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+ +
+
+

I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.

+ 1:32 PM - 12 Jan 2018 +
+
+
+
+
+ 107 Retweets +
+ +
+
+ + + +
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-self-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-self-property.spanish.md new file mode 100644 index 0000000000..bb70639f3b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-align-self-property.spanish.md @@ -0,0 +1,78 @@ +--- +id: 587d78af367417b2b2512b00 +title: Use the align-self Property +localeTitle: Usa la propiedad align-self. +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad final para elementos flexibles es align-self . Esta propiedad le permite ajustar la alineación de cada elemento individualmente, en lugar de configurarlos todos a la vez. Esto es útil ya que otras técnicas de ajuste comunes que utilizan las propiedades CSS float , clear y vertical-align no funcionan en elementos flexibles. +align-self acepta los mismos valores que align-items y anulará cualquier valor establecido por la propiedad align-items . +
+ +## Instructions +
+Agregue la propiedad CSS align-self a #box-1 y #box-2 . Dé a #box-1 un valor de centro y a #box-2 un valor de flex-end. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debe tener la propiedad align-self establecida en un valor de center.' + testString: 'assert($("#box-1").css("align-self") == "center", "The #box-1 element should have the align-self property set to a value of center.");' + - text: 'El elemento #box-2 debe tener la propiedad align-self establecida en un valor de flex-end.' + testString: 'assert($("#box-2").css("align-self") == "flex-end", "The #box-2 element should have the align-self property set to a value of flex-end.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-basis-property-to-set-the-initial-size-of-an-item.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-basis-property-to-set-the-initial-size-of-an-item.spanish.md new file mode 100644 index 0000000000..d3531e2dd0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-basis-property-to-set-the-initial-size-of-an-item.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d78ae367417b2b2512afd +title: Use the flex-basis Property to Set the Initial Size of an Item +localeTitle: Utilice la propiedad de base flexible para establecer el tamaño inicial de un artículo +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de flex-basis especifica el tamaño inicial del elemento antes de que CSS realice ajustes con flex-shrink o flex-grow . +Las unidades utilizadas por la propiedad de flex-basis son las mismas que otras propiedades de tamaño ( px , em , % , etc.). El valor auto dimensiona los elementos en función del contenido. +
+ +## Instructions +
+Establezca el tamaño inicial de las cajas utilizando flex-basis . Agregue la propiedad CSS flex-basis a #box-1 y #box-2 . Dé a #box-1 un valor de 10em y #box-2 un valor de 20em . +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debería tener una propiedad de flex-basis .' + testString: 'assert($("#box-1").css("flex-basis") != "auto", "The #box-1 element should have a flex-basis property.");' + - text: 'El elemento #box-1 debe tener un valor de flex-basis de 10em '. + testString: 'assert(code.match(/#box-1\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?10em;/g), "The #box-1 element should have a flex-basis value of 10em.");' + - text: 'El elemento #box-2 debería tener la propiedad de flex-basis .' + testString: 'assert($("#box-2").css("flex-basis") != "auto", "The #box-2 element should have the flex-basis property.");' + - text: 'El elemento #box-2 debe tener un valor de flex-basis de 20em '. + testString: 'assert(code.match(/#box-2\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?20em;/g), "The #box-2 element should have a flex-basis value of 20em.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-column.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-column.spanish.md new file mode 100644 index 0000000000..17c01aded1 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-column.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d78ac367417b2b2512af4 +title: Use the flex-direction Property to Make a Column +localeTitle: Usa la propiedad de dirección flexible para hacer una columna +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Los dos últimos desafíos utilizaron la propiedad de flex-direction establecida en fila. Esta propiedad también puede crear una columna apilando verticalmente los hijos de un contenedor flexible. +
+ +## Instructions +
+Agregue la propiedad CSS flex-direction al elemento #box-container y asígnele un valor de columna. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-container debería tener una propiedad de flex-direction configurada en columna.' + testString: 'assert($("#box-container").css("flex-direction") == "column", "The #box-container element should have a flex-direction property set to column.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-row.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-row.spanish.md new file mode 100644 index 0000000000..51e369633a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-row.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d78ab367417b2b2512af2 +title: Use the flex-direction Property to Make a Row +localeTitle: Utilice la propiedad de dirección flexible para hacer una fila +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Agregar display: flex a un elemento lo convierte en un contenedor flexible. Esto hace posible alinear cualquier elemento secundario de ese elemento en filas o columnas. Para ello, agregue la propiedad de flex-direction al elemento principal y configúrelo en fila o columna. La creación de una fila alineará a los hijos horizontalmente, y la creación de una columna alineará a los hijos verticalmente. +Otras opciones para flex-direction son la fila-reversa y la columna-reversa. +Nota
El valor predeterminado para la propiedad de flex-direction es fila. +
+ +## Instructions +
+Agregue la propiedad CSS flex-direction al elemento #box-container y asígnele un valor de fila-reversa. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-container debería tener una propiedad de flex-direction configurada para invertir la fila.' + testString: 'assert($("#box-container").css("flex-direction") == "row-reverse", "The #box-container element should have a flex-direction property set to row-reverse.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-grow-property-to-expand-items.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-grow-property-to-expand-items.spanish.md new file mode 100644 index 0000000000..6fc61e6e78 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-grow-property-to-expand-items.spanish.md @@ -0,0 +1,77 @@ +--- +id: 587d78ae367417b2b2512afc +title: Use the flex-grow Property to Expand Items +localeTitle: Utilice la propiedad flex-grow para expandir elementos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Lo opuesto a flex-shrink es la propiedad de flex-grow . Recuerde que flex-shrink controla el tamaño de los elementos cuando el contenedor se reduce. La propiedad flex-grow controla el tamaño de los elementos cuando el contenedor principal se expande. +Usando un ejemplo similar del último desafío, si un elemento tiene un valor de flex-grow de 1 y el otro tiene un valor de flex-grow de 3, el valor de 3 crecerá tres veces más que el otro. +
+ +## Instructions +
+Agregue la propiedad CSS flex-grow a #box-1 y #box-2 . Dé a #box-1 un valor de 1 y #box-2 un valor de 2. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debe tener la propiedad flex-grow establecida en un valor de 1.' + testString: 'assert($("#box-1").css("flex-grow") == "1", "The #box-1 element should have the flex-grow property set to a value of 1.");' + - text: 'El elemento #box-2 debe tener la propiedad flex-grow establecida en un valor de 2.' + testString: 'assert($("#box-2").css("flex-grow") == "2", "The #box-2 element should have the flex-grow property set to a value of 2.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shorthand-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shorthand-property.spanish.md new file mode 100644 index 0000000000..598d04781b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shorthand-property.spanish.md @@ -0,0 +1,80 @@ +--- +id: 587d78ae367417b2b2512afe +title: Use the flex Shorthand Property +localeTitle: Utilice la propiedad de la taquigrafía de flex +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hay un acceso directo disponible para configurar varias propiedades de flexión a la vez. Las propiedades flex-grow , flex-shrink y flex-basis pueden establecerse mediante el uso de la propiedad flex . +Por ejemplo, flex: 1 0 10px; establecerá el elemento para flex-grow: 1; , flex-shrink: 0; , y flex-basis: 10px; . +La configuración predeterminada de las propiedades es flex: 0 1 auto; . +
+ +## Instructions +
+Agregue la propiedad CSS flex tanto a #box-1 como #box-2 . Dé a #box-1 los valores para que su flex-grow sea ​​2, flex-shrink sea ​​2, y su flex-basis sea ​​150px. Dé a #box-2 los valores para que su flex-grow sea ​​1, flex-shrink sea ​​1, y su flex-basis sea ​​150px. +Estos valores harán que #box-1 crezca para llenar el espacio adicional al doble de la tasa de #box-2 cuando el contenedor es mayor que 300px y se contraerá al doble de la tasa de #box-2 cuando el contenedor sea menor de 300px . 300px es el tamaño combinado de los valores de flex-basis de las dos cajas. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debe tener la propiedad flex establecida en un valor de 2 2 150px.' + testString: 'assert($("#box-1").css("flex-grow") == "2" && $("#box-1").css("flex-shrink") == "2" && $("#box-1").css("flex-basis") == "150px", "The #box-1 element should have the flex property set to a value of 2 2 150px.");' + - text: 'El elemento #box-2 debe tener la propiedad flex establecida en un valor de 1 1 150px.' + testString: 'assert($("#box-2").css("flex-grow") == "1" && $("#box-2").css("flex-shrink") == "1" && $("#box-2").css("flex-basis") == "150px", "The #box-2 element should have the flex property set to a value of 1 1 150px.");' + - text: 'Su código debe usar la propiedad flex para #box-1 y #box-2 .' + testString: 'assert(code.match(/flex:\s*?\d\s+?\d\s+?150px;/g).length == 2, "Your code should use the flex property for #box-1 and #box-2.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shrink-property-to-shrink-items.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shrink-property-to-shrink-items.spanish.md new file mode 100644 index 0000000000..34f62a3e1a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-shrink-property-to-shrink-items.spanish.md @@ -0,0 +1,79 @@ +--- +id: 587d78ad367417b2b2512afb +title: Use the flex-shrink Property to Shrink Items +localeTitle: Utilice la propiedad flex-shrink para reducir artículos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hasta ahora, todas las propiedades en los desafíos se aplican al contenedor de flexión (el elemento principal de los elementos de flexión). Sin embargo, hay varias propiedades útiles para los elementos flexibles. +La primera es la propiedad flex-shrink . Cuando se usa, permite que un elemento se encoja si el contenedor flexible es demasiado pequeño. Los elementos se reducen cuando el ancho del contenedor principal es menor que el ancho combinado de todos los elementos flexibles dentro de él. +La propiedad flex-shrink toma números como valores. Cuanto mayor sea el número, más se reducirá en comparación con los otros elementos del contenedor. Por ejemplo, si un elemento tiene un valor de flex-shrink de 1 y el otro tiene un valor de flex-shrink de 3, el valor de 3 se contraerá tres veces más que el otro. +
+ +## Instructions +
+Agregue la propiedad CSS flex-shrink a #box-1 y #box-2 . Dé a #box-1 un valor de 1 y #box-2 un valor de 2. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debe tener la propiedad flex-shrink establecida en un valor de 1'. + testString: 'assert($("#box-1").css("flex-shrink") == "1", "The #box-1 element should have the flex-shrink property set to a value of 1.");' + - text: 'El elemento #box-2 debe tener la propiedad flex-shrink establecida en un valor de 2'. + testString: 'assert($("#box-2").css("flex-shrink") == "2", "The #box-2 element should have the flex-shrink property set to a value of 2.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-wrap-property-to-wrap-a-row-or-column.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-wrap-property-to-wrap-a-row-or-column.spanish.md new file mode 100644 index 0000000000..44d2d21339 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-flex-wrap-property-to-wrap-a-row-or-column.spanish.md @@ -0,0 +1,102 @@ +--- +id: 587d78ad367417b2b2512afa +title: Use the flex-wrap Property to Wrap a Row or Column +localeTitle: Utilice la propiedad flex-wrap para envolver una fila o columna +challengeType: 0 +videoUrl: '' +--- + +## Description +
+CSS flexbox tiene una función para dividir un elemento flexible en varias filas (o columnas). Por defecto, un contenedor flexible encajará todos los elementos flexibles juntos. Por ejemplo, una fila estará en una sola línea. +Sin embargo, al usar la propiedad flex-wrap , le dice a CSS que envuelva los elementos. Esto significa que los elementos adicionales se mueven a una nueva fila o columna. El punto de ruptura de donde ocurre la envoltura depende del tamaño de los artículos y del tamaño del contenedor. +CSS también tiene opciones para la dirección de la envoltura: + +
+ +## Instructions +
+El diseño actual tiene demasiados cuadros para una fila. Agregue la propiedad CSS flex-wrap al elemento #box-container y asígnele un valor de wrap. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-container debería tener la propiedad flex-wrap establecida en un valor de wrap.' + testString: 'assert($("#box-container").css("flex-wrap") == "wrap", "The #box-container element should have the flex-wrap property set to a value of wrap.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-justify-content-property-in-the-tweet-embed.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-justify-content-property-in-the-tweet-embed.spanish.md new file mode 100644 index 0000000000..b1b1692468 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-justify-content-property-in-the-tweet-embed.spanish.md @@ -0,0 +1,142 @@ +--- +id: 587d78ac367417b2b2512af7 +title: Use the justify-content Property in the Tweet Embed +localeTitle: Use la propiedad justify-content en el Tweet Insertar +challengeType: 0 +videoUrl: '' +--- + +## Description +
+El último desafío mostró un ejemplo de la propiedad justify-content . Para la inserción de tweets, esta propiedad se puede aplicar para alinear los elementos en el elemento .profile-name . +
+ +## Instructions +
+Añadir la propiedad CSS justify-content de la cabecera del .profile-name del elemento y establezca el valor en cualquiera de las opciones desde el último desafío. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento .profile-name debe tener la propiedad .profile-name justify-content establecida en cualquiera de estos valores: centro, inicio flexible, extremo flexible, espacio intermedio o espacio-alrededor.' + testString: 'assert(code.match(/header\s.profile-name\s*{\s*?.*?\s*?.*?\s*?\s*?.*?\s*?justify-content\s*:\s*(center|flex-start|flex-end|space-between|space-around)\s*;/g), "The .profile-name element should have the justify-content property set to any of these values: center, flex-start, flex-end, space-between, or space-around.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+ Quincy Larson's profile picture +
+

Quincy Larson

+

@ossia

+
+ +
+
+

I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.

+ 1:32 PM - 12 Jan 2018 +
+
+
+
+
+ 107 Retweets +
+ +
+
+ + + +
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "header .profile-name {display: flex; flex-direction: column; justify-content: center; margin-left: 10px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-order-property-to-rearrange-items.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-order-property-to-rearrange-items.spanish.md new file mode 100644 index 0000000000..6d48ebd4da --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-flexbox/use-the-order-property-to-rearrange-items.spanish.md @@ -0,0 +1,77 @@ +--- +id: 587d78ae367417b2b2512aff +title: Use the order Property to Rearrange Items +localeTitle: Utilice la propiedad de orden para reorganizar artículos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad order se usa para decirle a CSS el orden en que aparecen los elementos flexibles en el contenedor flex. De forma predeterminada, los elementos aparecerán en el mismo orden en que vienen en el código fuente HTML. La propiedad toma números como valores y se pueden usar números negativos. +
+ +## Instructions +
+Agregue el order propiedades CSS a #box-1 y #box-2 . Dé a #box-1 un valor de 2 y a #box-2 un valor de 1. +
+ +## Tests +
+ +```yml +tests: + - text: 'El elemento #box-1 debe tener la propiedad de order establecida en un valor de 2.' + testString: 'assert($("#box-1").css("order") == "2", "The #box-1 element should have the order property set to a value of 2.");' + - text: 'El elemento #box-2 debe tener la propiedad de order establecida en un valor de 1.' + testString: 'assert($("#box-2").css("order") == "1", "The #box-2 element should have the order property set to a value of 1.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
+
+
+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-columns-with-grid-template-columns.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-columns-with-grid-template-columns.spanish.md new file mode 100644 index 0000000000..7eba046b74 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-columns-with-grid-template-columns.spanish.md @@ -0,0 +1,82 @@ +--- +id: 5a9036d038fddaf9a66b5d32 +title: Add Columns with grid-template-columns +localeTitle: Añadir columnas con cuadrícula-plantilla-columnas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Simplemente crear un elemento de cuadrícula no te lleva muy lejos. También es necesario definir la estructura de la cuadrícula. Para agregar algunas columnas a la cuadrícula, use la propiedad grid-template-columns en un contenedor de cuadrícula como se muestra a continuación: +
.container {
  display: grid;
  grid-template-columns: 50px 50px;
}
+Esto le dará a su cuadrícula dos columnas de 50px de ancho cada una. +El número de parámetros dados a la propiedad grid-template-columns indica el número de columnas en la cuadrícula, y el valor de cada parámetro indica el ancho de cada columna. +
+ +## Instructions +
+Déle al contenedor de la cuadrícula tres columnas de 100px ancho cada una. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-template-columns con tres unidades de 100px . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?100px\s*?100px\s*?100px\s*?;[\s\S]*}/gi), "container class should have a grid-template-columns property with three units of 100px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: 100px 100px 100px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-gaps-faster-with-grid-gap.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-gaps-faster-with-grid-gap.spanish.md new file mode 100644 index 0000000000..d0330b5299 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-gaps-faster-with-grid-gap.spanish.md @@ -0,0 +1,81 @@ +--- +id: 5a9036ee38fddaf9a66b5d37 +title: Add Gaps Faster with grid-gap +localeTitle: Agregue espacios más rápido con la rejilla +challengeType: 0 +videoUrl: '' +--- + +## Description +
+grid-gap es una propiedad abreviada grid-row-gap y grid-column-gap de los dos desafíos anteriores que es más conveniente de usar. Si grid-gap tiene un valor, creará un gap entre todas las filas y columnas. Sin embargo, si hay dos valores, utilizará el primero para establecer el espacio entre las filas y el segundo valor para las columnas. +
+ +## Instructions +
+Use grid-gap para introducir un espacio de 10px entre las filas y un espacio de 20px entre las columnas. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-gap que introduce 10px espacio de 10px entre las filas y un espacio de 20px entre las columnas. + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-gap\s*?:\s*?10px\s+?20px\s*?;[\s\S]*}/gi), "container class should have a grid-gap property that introduces 10px gap between the rows and 20px gap between the columns.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-gap: 10px 20px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-rows-with-grid-template-rows.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-rows-with-grid-template-rows.spanish.md new file mode 100644 index 0000000000..638205b4c6 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/add-rows-with-grid-template-rows.spanish.md @@ -0,0 +1,80 @@ +--- +id: 5a9036e138fddaf9a66b5d33 +title: Add Rows with grid-template-rows +localeTitle: Añadir filas con cuadrícula-filas-plantilla +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La cuadrícula que creó en el último desafío establecerá el número de filas automáticamente. Para ajustar las filas manualmente, use la propiedad grid-template-rows de la misma forma que usó grid-template-columns en el desafío anterior. +
+ +## Instructions +
+Agregue dos filas a la cuadrícula que tengan 50px altura cada una. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad grid-template-rows con dos unidades de 50px . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-rows\s*?:\s*?50px\s*?50px\s*?;[\s\S]*}/gi), "container class should have a grid-template-rows property with two units of 50px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-rows: 50px 50px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-horizontally-using-justify-items.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-horizontally-using-justify-items.spanish.md new file mode 100644 index 0000000000..ec1a424c8e --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-horizontally-using-justify-items.spanish.md @@ -0,0 +1,83 @@ +--- +id: 5a90376038fddaf9a66b5d3c +title: Align All Items Horizontally using justify-items +localeTitle: Alinear todos los elementos horizontalmente utilizando elementos justificados +challengeType: 0 +videoUrl: '' +--- + +## Description +
+A veces desea que todos los elementos en su Cuadrícula de CSS compartan la misma alineación. Puede usar las propiedades aprendidas anteriormente y alinearlas individualmente, o puede alinearlas todas a la vez de forma horizontal mediante el uso justify-items en su contenedor de cuadrícula. Esta propiedad puede aceptar todos los valores que aprendió en los dos desafíos anteriores, con la diferencia de que moverá todos los elementos de nuestra cuadrícula a la alineación deseada. +
+ +## Instructions +
+Utilice esta propiedad para centrar todos nuestros artículos horizontalmente. +
+ +## Tests +
+ +```yml +tests: + - text: container clase de container debe tener una propiedad de justify-items que tenga el valor de center . + testString: 'assert(code.match(/.container\s*?{[\s\S]*justify-items\s*?:\s*?center\s*?;[\s\S]*}/gi), "container class should have a justify-items property that has the value of center.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {justify-items: center;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-vertically-using-align-items.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-vertically-using-align-items.spanish.md new file mode 100644 index 0000000000..4b4fa8450e --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-all-items-vertically-using-align-items.spanish.md @@ -0,0 +1,83 @@ +--- +id: 5a94fdf869fb03452672e45b +title: Align All Items Vertically using align-items +localeTitle: Alinear todos los elementos verticalmente utilizando elementos de alineación +challengeType: 0 +videoUrl: '' +--- + +## Description +
+uso de la propiedad align-items en un contenedor de cuadrícula establecerá la alineación vertical para todos los elementos en nuestra cuadrícula. +
+ +## Instructions +
+Úselo ahora para mover todos los elementos al final de cada celda. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad align-items que tenga el valor de end . + testString: 'assert(code.match(/.container\s*?{[\s\S]*align-items\s*?:\s*?end\s*?;[\s\S]*}/gi), "container class should have a align-items property that has the value of end.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {align-items: end;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-horizontally-using-justify-self.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-horizontally-using-justify-self.spanish.md new file mode 100644 index 0000000000..f42df65af9 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-horizontally-using-justify-self.spanish.md @@ -0,0 +1,90 @@ +--- +id: 5a90374338fddaf9a66b5d3a +title: Align an Item Horizontally using justify-self +localeTitle: Alinear un artículo horizontalmente usando justify-self +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En CSS Grid, el contenido de cada elemento se encuentra en un cuadro al que se hace referencia como una celda . Puede alinear la posición del contenido dentro de su celda horizontalmente usando la propiedad de justify-self en un elemento de la cuadrícula. De forma predeterminada, esta propiedad tiene un valor de stretch , que hará que el contenido llene todo el ancho de la celda. Esta propiedad de la cuadrícula de CSS también acepta otros valores: +start : alinea el contenido a la izquierda de la celda, +center : alinea el contenido en el centro de la celda, +end : alinea el contenido a la derecha de la celda. +
+ +## Instructions +
+Use la propiedad de justify-self para centrar el elemento con la clase item2 . +
+ +## Tests +
+ +```yml +tests: + - text: item2 clase item2 debe tener una propiedad de justify-self que tenga el valor de center . + testString: 'assert(code.match(/.item2\s*?{[\s\S]*justify-self\s*?:\s*?center\s*?;[\s\S]*}/gi), "item2 class should have a justify-self property that has the value of center.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item2 {justify-self: center;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-vertically-using-align-self.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-vertically-using-align-self.spanish.md new file mode 100644 index 0000000000..11c4512a16 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/align-an-item-vertically-using-align-self.spanish.md @@ -0,0 +1,87 @@ +--- +id: 5a90375238fddaf9a66b5d3b +title: Align an Item Vertically using align-self +localeTitle: Alinear un elemento verticalmente con align-self +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Al igual que puede alinear un elemento horizontalmente, también hay una forma de alinear un elemento verticalmente. Para hacer esto, utiliza la propiedad align-self en un elemento. Esta propiedad acepta todos los mismos valores como justify-self del último desafío. +
+ +## Instructions +
+Alinee el elemento con la clase item3 verticalmente al end . +
+ +## Tests +
+ +```yml +tests: + - text: item3 clase item3 debe tener una propiedad align-self que tenga el valor de end . + testString: 'assert(code.match(/.item3\s*?{[\s\S]*align-self\s*?:\s*?end\s*?;[\s\S]*}/gi), "item3 class should have a align-self property that has the value of end.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item3 {align-self: end;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-column-gap-using-grid-column-gap.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-column-gap-using-grid-column-gap.spanish.md new file mode 100644 index 0000000000..02e4d0955d --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-column-gap-using-grid-column-gap.spanish.md @@ -0,0 +1,84 @@ +--- +id: 5a9036ee38fddaf9a66b5d35 +title: Create a Column Gap Using grid-column-gap +localeTitle: Crear una brecha de columna usando grid-column-gap +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hasta ahora, en las cuadrículas que has creado, las columnas han estado apretadas una contra la otra. A veces quieres un espacio entre las columnas. Para agregar un espacio entre las columnas, use la propiedad grid-column-gap así: +
grid-column-gap: 10px;
+Esto crea 10 px de espacio vacío entre todas nuestras columnas. +
+ +## Instructions +
+Dé a las columnas en la cuadrícula un espacio de 20px . +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad grid-column-gap que tenga el valor de 20px . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-column-gap\s*?:\s*?20px\s*?;[\s\S]*}/gi), "container class should have a grid-column-gap property that has the value of 20px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-column-gap: 20px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-row-gap-using-grid-row-gap.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-row-gap-using-grid-row-gap.spanish.md new file mode 100644 index 0000000000..9d46051a7a --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-a-row-gap-using-grid-row-gap.spanish.md @@ -0,0 +1,82 @@ +--- +id: 5a9036ee38fddaf9a66b5d36 +title: Create a Row Gap using grid-row-gap +localeTitle: Crear un espacio en la fila usando la rejilla-fila-espacio +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Se puede añadir un espacio entre las filas de una cuadrícula utilizando grid-row-gap de la misma manera que ha agregado un espacio entre columnas en el desafío anterior. +
+ +## Instructions +
+Crea un espacio para las filas que tiene 5px altura. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad grid-row-gap que tenga el valor de 5px . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-row-gap\s*?:\s*?5px\s*?;[\s\S]*}/gi), "container class should have a grid-row-gap property that has the value of 5px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-row-gap: 5px;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fill.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fill.spanish.md new file mode 100644 index 0000000000..fbe9b12f7b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fill.spanish.md @@ -0,0 +1,104 @@ +--- +id: 5a94fe5469fb03452672e461 +title: Create Flexible Layouts Using auto-fill +localeTitle: Crear diseños flexibles con autocompletar +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La función de repetición viene con una opción llamada autocompletar . Esto le permite insertar automáticamente tantas filas o columnas del tamaño deseado como sea posible, dependiendo del tamaño del contenedor. Puede crear diseños flexibles al combinar auto-fill con minmax . +En la vista previa, grid-template-columns se establece en +
repeat(auto-fill, minmax(60px, 1fr));
+Cuando el contenedor cambia de tamaño, esta configuración continúa insertando columnas de 60px y estirándolas hasta que pueda insertar otra. +Nota
Si su contenedor no puede colocar todos sus artículos en una fila, los moverá a uno nuevo. +
+ +## Instructions +
+En la primera cuadrícula, use auto-fill con repeat para llenar la cuadrícula con columnas que tengan un ancho mínimo de 60px y un máximo de 1fr . Luego cambie el tamaño de la vista previa para ver la acción de autocompletar. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-template-columns con repeat y auto-fill que llenará la cuadrícula con columnas que tengan un ancho mínimo de 60px y un máximo de 1fr . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?auto-fill\s*?,\s*?minmax\s*?\(\s*?60px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi), "container class should have a grid-template-columns property with repeat and auto-fill that will fill the grid with columns that have a minimum width of 60px and maximum of 1fr.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + +
+
1
+
2
+
3
+
4
+
5
+
+
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: repeat(auto-fill, minmax(60px, 1fr));}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fit.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fit.spanish.md new file mode 100644 index 0000000000..7c9093e5f0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-flexible-layouts-using-auto-fit.spanish.md @@ -0,0 +1,102 @@ +--- +id: 5a94fe6269fb03452672e462 +title: Create Flexible Layouts Using auto-fit +localeTitle: Crear diseños flexibles con autoajuste +challengeType: 0 +videoUrl: '' +--- + +## Description +
+auto-fit funciona de manera casi idéntica al auto-fill . La única diferencia es que cuando el tamaño del contenedor excede el tamaño de todos los elementos combinados, el auto-fill continúa insertando filas o columnas vacías y empuja sus artículos hacia un lado, mientras que auto-fit colapsa esas filas o columnas vacías y extiende sus artículos a Ajustar el tamaño del contenedor. +Nota
Si su contenedor no puede colocar todos sus artículos en una fila, los moverá a uno nuevo. +
+ +## Instructions +
+En la segunda cuadrícula, use auto-fit con repeat para llenar la cuadrícula con columnas que tengan un ancho mínimo de 60px y máximo de 1fr . Luego cambia el tamaño de la vista previa para ver la diferencia. +
+ +## Tests +
+ +```yml +tests: + - text: container2 clase container2 debe tener una propiedad de grid-template-columns con repeat y auto-fit que llenará la cuadrícula con columnas que tengan un ancho mínimo de 60px y máximo de 1fr . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?auto-fit\s*?,\s*?minmax\s*?\(\s*?60px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi), "container2 class should have a grid-template-columns property with repeat and auto-fit that will fill the grid with columns that have a minimum width of 60px and maximum of 1fr.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: repeat( auto-fill, minmax(60px, 1fr));} .container2 {grid-template-columns: repeat(auto-fit, minmax(60px, 1fr));}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-grids-within-grids.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-grids-within-grids.spanish.md new file mode 100644 index 0000000000..52b3f6a866 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-grids-within-grids.spanish.md @@ -0,0 +1,114 @@ +--- +id: 5a94fe8569fb03452672e464 +title: Create Grids within Grids +localeTitle: Crear cuadrículas dentro de cuadrículas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Convertir un elemento en una cuadrícula solo afecta el comportamiento de sus descendientes directos. Entonces, al convertir un descendiente directo en una cuadrícula, tiene una cuadrícula dentro de una cuadrícula. +Por ejemplo, al configurar las propiedades de display y grid-template-columns del elemento con la clase item3 , creará una cuadrícula dentro de su cuadrícula. +
+ +## Instructions +
+Convierta el elemento con la clase item3 en una cuadrícula con dos columnas con un ancho de auto y 1fr usando las 1fr display y grid-template-columns . +
+ +## Tests +
+ +```yml +tests: + - text: item3 clase item3 debe tener una propiedad grid-template-columns con auto y 1fr como valores. + testString: 'assert(code.match(/.item3\s*?{[\s\S]*grid-template-columns\s*?:\s*?auto\s*?1fr\s*?;[\s\S]*}/gi), "item3 class should have a grid-template-columns property with auto and 1fr as values.");' + - text: item3 clase item3 debe tener una propiedad de display con el valor de grid . + testString: 'assert(code.match(/.item3\s*?{[\s\S]*display\s*?:\s*?grid\s*?;[\s\S]*}/gi), "item3 class should have a display property with the value of grid.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
header
+
advert
+
+
paragraph1
+
paragraph2
+
+
footer
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item3 {grid-template-columns: auto 1fr; display: grid;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-your-first-css-grid.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-your-first-css-grid.spanish.md new file mode 100644 index 0000000000..fe1fe0ac60 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/create-your-first-css-grid.spanish.md @@ -0,0 +1,79 @@ +--- +id: 5a858944d96184f06fd60d61 +title: Create Your First CSS Grid +localeTitle: Crea tu primera cuadrícula CSS +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Convierta cualquier elemento HTML en un contenedor de cuadrícula estableciendo su propiedad de display en grid . Esto le da la posibilidad de usar todas las demás propiedades asociadas con CSS Grid. +Nota
En CSS Grid, el elemento padre se conoce como el contenedor y sus hijos se denominan elementos . +
+ +## Instructions +
+Cambie la visualización del div con la clase de container a grid . +
+ +## Tests +
+ +```yml +tests: + - text: clase de container debe tener una propiedad de display con un valor de grid . + testString: 'assert(code.match(/.container\s*?{[\s\S]*display\s*?:\s*?grid\s*?;[\s\S]*}/gi), "container class should have a display property with a value of grid.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {display: grid;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/divide-the-grid-into-an-area-template.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/divide-the-grid-into-an-area-template.spanish.md new file mode 100644 index 0000000000..212d1548a0 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/divide-the-grid-into-an-area-template.spanish.md @@ -0,0 +1,90 @@ +--- +id: 5a94fe0569fb03452672e45c +title: Divide the Grid Into an Area Template +localeTitle: Divide la cuadrícula en una plantilla de área +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede agrupar las celdas de su cuadrícula en un área y darle al área un nombre personalizado. Haga esto utilizando grid-template-areas en el contenedor como esto: +
grid-template-areas:
  "header header header"
  "advert content content"
  "footer footer footer";
+El código anterior combina las tres celdas superiores juntas en un área llamada header , las tres celdas inferiores en un área de footer , y forma dos áreas en la fila central; advert y content . +Nota
Cada palabra en el código representa una celda y cada par de comillas representa una fila. +Además de las etiquetas personalizadas, puede usar un punto ( . ) Para designar una celda vacía en la cuadrícula. +
+ +## Instructions +
+Coloque la plantilla de área para que la celda etiquetada como advert convierta en una celda vacía. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-template-areas similar a la vista previa, pero tiene . En lugar del área de advert . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-areas\s*?:\s*?"\s*?header\s*?header\s*?header\s*?"\s*?"\s*?.\s*?content\s*?content\s*?"\s*?"\s*?footer\s*?footer\s*?footer\s*?"\s*?;[\s\S]*}/gi), "container class should have a grid-template-areas propertiy similar to the preview but has . instead of the advert area.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-areas: \"header header header\" \". content content\" \"footer footer footer\";}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/limit-item-size-using-the-minmax-function.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/limit-item-size-using-the-minmax-function.spanish.md new file mode 100644 index 0000000000..6962e6edd4 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/limit-item-size-using-the-minmax-function.spanish.md @@ -0,0 +1,85 @@ +--- +id: 5a94fe4469fb03452672e460 +title: Limit Item Size Using the minmax Function +localeTitle: Limitar el tamaño del elemento utilizando la función minmax +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hay otra función incorporada para usar con grid-template-columns grid-template-rows llamada minmax . Se utiliza para limitar el tamaño de los elementos cuando el contenedor de cuadrícula cambia de tamaño. Para hacer esto, necesita especificar el rango de tamaño aceptable para su artículo. Aquí hay un ejemplo: +
grid-template-columns: 100px minmax(50px, 200px);
+En el código anterior, grid-template-columns está configurado para crear dos columnas; el primero tiene un ancho de 100 px y el segundo tiene el ancho mínimo de 50 px y el ancho máximo de 200 px. +
+ +## Instructions +
+Con la función minmax , reemplace el 1fr en la función de repeat con un tamaño de columna que tenga el ancho mínimo de 90px y el ancho máximo de 1fr , y 1fr tamaño del panel de vista previa para ver el efecto. +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-template-columns que está configurada para repetir 3 columnas con un ancho mínimo de 90px y un ancho máximo de 1fr . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?3\s*?,\s*?minmax\s*?\(\s*?90px\s*?,\s*?1fr\s*?\)\s*?\)\s*?;[\s\S]*}/gi), "container class should have a grid-template-columns property that is set to repeat 3 columns with the minimum width of 90px and maximum width of 1fr.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: repeat(3, minmax(90px, 1fr));}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/place-items-in-grid-areas-using-the-grid-area-property.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/place-items-in-grid-areas-using-the-grid-area-property.spanish.md new file mode 100644 index 0000000000..fd7166b100 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/place-items-in-grid-areas-using-the-grid-area-property.spanish.md @@ -0,0 +1,92 @@ +--- +id: 5a94fe1369fb03452672e45d +title: Place Items in Grid Areas Using the grid-area Property +localeTitle: Colocar elementos en áreas de cuadrícula utilizando la propiedad de área de cuadrícula +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Después de crear una plantilla de áreas para su contenedor de cuadrícula, como se muestra en el desafío anterior, puede colocar un elemento en su área personalizada haciendo referencia al nombre que le dio. Para hacer esto, usa la propiedad del grid-area la grid-area en un elemento como este: +
.item1 { grid-area: header; }
+Esto le permite a la cuadrícula saber que desea que la clase item1 en el área denominada header . En este caso, el elemento utilizará toda la fila superior porque toda esa fila se denomina área de encabezado. +
+ +## Instructions +
+Coloque un elemento con la clase item5 en el área del footer usando la propiedad del grid-area la grid-area . +
+ +## Tests +
+ +```yml +tests: + - text: item5 clase item5 debe tener una propiedad de grid-area que tenga el valor de footer de footer . + testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?footer\s*?;[\s\S]*}/gi), "item5 class should have a grid-area property that has the value of footer.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item5 {grid-area: footer;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/reduce-repetition-using-the-repeat-function.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/reduce-repetition-using-the-repeat-function.spanish.md new file mode 100644 index 0000000000..7afce46869 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/reduce-repetition-using-the-repeat-function.spanish.md @@ -0,0 +1,91 @@ +--- +id: 5a94fe3669fb03452672e45f +title: Reduce Repetition Using the repeat Function +localeTitle: Reducir la repetición usando la función de repetición +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Cuando usó grid-template-columns grid-template-rows para definir la estructura de una cuadrícula, ingresó un valor para cada fila o columna que creó. +Digamos que desea una cuadrícula con 100 filas de la misma altura. No es muy práctico insertar 100 valores individualmente. Afortunadamente, hay una mejor manera: utilizando la función de repeat para especificar el número de veces que desea que se repita su columna o fila, seguido de una coma y el valor que desea repetir. +Aquí hay un ejemplo que crearía la cuadrícula de 100 filas, cada fila a 50px de altura. +
grid-template-rows: repeat(100, 50px);
+También puede repetir varios valores con la función de repetición e insertar la función entre otros valores al definir una estructura de cuadrícula. Esto es lo que quiero decir: +
grid-template-columns: repeat(2, 1fr 50px) 20px;
+Esto se traduce en: +
grid-template-columns: 1fr 50px 1fr 50px 20px;
+Nota
1fr 50px se repite dos veces seguidas de 20px. +
+ +## Instructions +
+Use repeat para eliminar la repetición de la propiedad grid-template-columns . +
+ +## Tests +
+ +```yml +tests: + - text: container clase container debe tener una propiedad de grid-template-columns que está configurada para repetir 3 columnas con el ancho de 1fr . + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?repeat\s*?\(\s*?3\s*?,\s*?1fr\s*?\)\s*?;[\s\S]*}/gi), "container class should have a grid-template-columns property that is set to repeat 3 columns with the width of 1fr.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: repeat(3, 1fr);}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-css-grid-units-to-change-the-size-of-columns-and-rows.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-css-grid-units-to-change-the-size-of-columns-and-rows.spanish.md new file mode 100644 index 0000000000..05d2071052 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-css-grid-units-to-change-the-size-of-columns-and-rows.spanish.md @@ -0,0 +1,87 @@ +--- +id: 5a9036ee38fddaf9a66b5d34 +title: Use CSS Grid units to Change the Size of Columns and Rows +localeTitle: Utilice las unidades de cuadrícula de CSS para cambiar el tamaño de las columnas y las filas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Puede usar unidades absolutas y relativas como px y em en CSS Grid para definir el tamaño de las filas y columnas. También puede usar estos: +fr : establece la columna o fila a una fracción del espacio disponible, +auto : establece la columna o fila al ancho o alto de su contenido automáticamente, +% : ajusta la columna o fila a El porcentaje de ancho de su contenedor. +Aquí está el código que genera el resultado en la vista previa: +
grid-template-columns: auto 50px 10% 2fr 1fr;
+Este fragmento crea cinco columnas. La primera columna es tan ancha como su contenido, la segunda columna es 50px, la tercera columna es el 10% de su contenedor, y para las dos últimas columnas; El espacio restante se divide en tres secciones, dos se asignan para la cuarta columna y una para la quinta. +
+ +## Instructions +
+Haz una cuadrícula con tres columnas cuyos anchos sean los siguientes: 1fr, 100px y 2fr. +
+ +## Tests +
+ +```yml +tests: + - text: 'la clase container debe tener una propiedad de grid-template-columns que tenga tres columnas con los siguientes anchos: 1fr, 100px, and 2fr '. + testString: 'assert(code.match(/.container\s*?{[\s\S]*grid-template-columns\s*?:\s*?1fr\s*?100px\s*?2fr\s*?;[\s\S]*}/gi), "container class should have a grid-template-columns property that has three columns with the following widths: 1fr, 100px, and 2fr.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".container {grid-template-columns: 1fr 100px 2fr;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.spanish.md new file mode 100644 index 0000000000..3903e040bb --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-area-without-creating-an-areas-template.spanish.md @@ -0,0 +1,90 @@ +--- +id: 5a94fe2669fb03452672e45e +title: Use grid-area Without Creating an Areas Template +localeTitle: Usar área de cuadrícula sin crear una plantilla de áreas +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La propiedad de grid-area que aprendió en el último desafío se puede usar de otra manera. Si su cuadrícula no tiene una plantilla de áreas a la que hacer referencia, puede crear un área sobre la marcha para colocar un elemento como este: +
item1 { grid-area: 1/1/2/4; }
+Esto es usando los números de línea que aprendió anteriormente para definir dónde estará el área para este elemento. Los números en el ejemplo anterior representan estos valores: +
grid-area: horizontal line to start at / vertical line to start at / horizontal line to end at / vertical line to end at;
+Entonces, el elemento en el ejemplo consumirá las filas entre las líneas 1 y 2, y las columnas entre las líneas 1 y 4. +
+ +## Instructions +
+Usando la propiedad del grid-area la grid-area , coloque el elemento con la clase item5 entre las líneas horizontales tercera y cuarta y entre las líneas verticales primera y cuarta. +
+ +## Tests +
+ +```yml +tests: + - text: item5 clase item5 debe tener una propiedad de grid-area que tenga el valor de 3/1/4/4 . + testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-area\s*?:\s*?3\s*?\/\s*?1\s*?\/\s*?4\s*?\/\s*?4\s*?;[\s\S]*}/gi), "item5 class should have a grid-area property that has the value of 3/1/4/4.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item5 {grid-area: 3/1/4/4;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-column-to-control-spacing.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-column-to-control-spacing.spanish.md new file mode 100644 index 0000000000..9e9e2ce28e --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-column-to-control-spacing.spanish.md @@ -0,0 +1,93 @@ +--- +id: 5a90372638fddaf9a66b5d38 +title: Use grid-column to Control Spacing +localeTitle: Usa la cuadrícula para controlar el espaciado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hasta este punto, todas las propiedades que se han discutido son para contenedores de cuadrícula. La propiedad de la grid-column es la primera que se utiliza en los propios elementos de la cuadrícula. +Las líneas hipotéticas horizontales y verticales que crean la cuadrícula se denominan líneas . Estas líneas están numeradas comenzando con 1 en la esquina superior izquierda de la cuadrícula y se mueven hacia la derecha para columnas y hacia abajo para filas, contando hacia arriba. +Así es como se ven las líneas para una cuadrícula de 3x3: +

líneas de columna

1

2

3

4

líneas de fila

1

2

3

4

+Para controlar la cantidad de columnas que consumirá un elemento, puede usar la propiedad de la grid-column la grid-column junto con los números de línea en los que desea que comience y se detenga el elemento. +Aquí hay un ejemplo: +
grid-column: 1 / 3;
+Esto hará que el elemento comience en la primera línea vertical de la cuadrícula de la izquierda y se extienda hasta la tercera línea de la cuadrícula, consumiendo dos columnas. +
+ +## Instructions +
+Haga que el elemento con la clase item5 consuma las dos últimas columnas de la cuadrícula. +
+ +## Tests +
+ +```yml +tests: + - text: item5 clase debe tener una grid-column propiedad que tiene el valor de 2 / 4 . + testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-column\s*?:\s*?2\s*?\/\s*?4\s*?;[\s\S]*}/gi), "item5 class should have a grid-column property that has the value of 2 / 4.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item5 {grid-column: 2 / 4;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-row-to-control-spacing.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-row-to-control-spacing.spanish.md new file mode 100644 index 0000000000..cbe66d1208 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-grid-row-to-control-spacing.spanish.md @@ -0,0 +1,87 @@ +--- +id: 5a90373638fddaf9a66b5d39 +title: Use grid-row to Control Spacing +localeTitle: Usa la fila de la rejilla para controlar el espaciado +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Por supuesto, puede hacer que los artículos consuman varias filas al igual que con las columnas. Define las líneas horizontales en las que desea que comience y se detenga un elemento utilizando la propiedad de la grid-row la grid-row en un elemento de la cuadrícula. +
+ +## Instructions +
+Hacer que el elemento con la clase item5 consuma las dos últimas filas. +
+ +## Tests +
+ +```yml +tests: + - text: item5 clase debe tener una grid-row propiedad que tiene el valor de 2 / 4 . + testString: 'assert(code.match(/.item5\s*?{[\s\S]*grid-row\s*?:\s*?2\s*?\/\s*?4\s*?;[\s\S]*}/gi), "item5 class should have a grid-row property that has the value of 2 / 4.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
1
+
2
+
3
+
4
+
5
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = ".item5 {grid-row: 2 / 4;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-media-queries-to-create-responsive-layouts.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-media-queries-to-create-responsive-layouts.spanish.md new file mode 100644 index 0000000000..8b1f57aa88 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/css-grid/use-media-queries-to-create-responsive-layouts.spanish.md @@ -0,0 +1,122 @@ +--- +id: 5a94fe7769fb03452672e463 +title: Use Media Queries to Create Responsive Layouts +localeTitle: Utilice consultas de medios para crear diseños receptivos +challengeType: 0 +videoUrl: '' +--- + +## Description +
+CSS Grid puede ser una manera fácil de hacer que su sitio sea más receptivo al usar consultas de medios para reorganizar las áreas de la cuadrícula, cambiar las dimensiones de una cuadrícula y reorganizar la ubicación de los elementos. +En la vista previa, cuando el ancho de la ventana gráfica es de 300 px o más, el número de columnas cambia de 1 a 2. El área de publicidad ocupa la columna izquierda por completo. +
+ +## Instructions +
+Cuando el ancho de la ventana 400px sea ​​de 400px o más, haga que el área del encabezado ocupe la fila superior completamente y el área del pie de página ocupe la fila inferior completamente. +
+ +## Tests +
+ +```yml +tests: + - text: "Cuando la ventana 400px es de 400px o más, la clase de container debe tener una propiedad de grid-template-areas en la que las áreas de pie de página y encabezado ocupen las filas superior e inferior respectivamente, y el anuncio y el contenido ocupen las columnas izquierda y derecha de la fila central". + testString: 'assert(code.match(/@media\s*?\(\s*?min-width\s*?:\s*?400px\s*?\)[\s\S]*.container\s*?{[\s\S]*grid-template-areas\s*?:\s*?"\s*?header\s*?header\s*?"\s*?"\s*?advert\s*?content\s*?"\s*?"\s*?footer\s*?footer\s*?"\s*?;[\s\S]*}/gi), "When the viewport is 400px or more, container class should have a grid-template-areas property in which the footer and header areas occupy the top and bottom rows respectively and advert and content occupy the left and right columns of the middle row.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +
+
header
+
advert
+
content
+
footer
+
+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "@media (min-width: 400px){.container{ grid-template-areas: \"header header\" \"advert content\" \"footer footer\";}}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/create-a-media-query.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/create-a-media-query.spanish.md new file mode 100644 index 0000000000..875191db0b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/create-a-media-query.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d78b0367417b2b2512b08 +title: Create a Media Query +localeTitle: Crear una consulta de medios +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Las consultas de medios son una nueva técnica introducida en CSS3 que cambia la presentación del contenido en función de los diferentes tamaños de las vistas. La ventana gráfica es el área visible de un usuario de una página web y es diferente según el dispositivo utilizado para acceder al sitio. +Las consultas de medios consisten en un tipo de medio, y si ese tipo de medio coincide con el tipo de dispositivo en el que se muestra el documento, se aplican los estilos. Puede tener tantos selectores y estilos dentro de su consulta de medios como desee. +Este es un ejemplo de una consulta de medios que devuelve el contenido cuando el ancho del dispositivo es menor o igual a 100px: +@media (max-width: 100px) { /* CSS Rules */ } +y la siguiente consulta de medios devuelve el contenido cuando la altura del dispositivo es mayor o igual a 350px: +@media (min-height: 350px) { /* CSS Rules */ } +Recuerde, el CSS dentro de la consulta de medios se aplica solo si el tipo de medio coincide con el de el dispositivo que se está utilizando. +
+ +## Instructions +
+Agregue una consulta de medios, de modo que la etiqueta p tenga un font-size de font-size de 10 px cuando la altura del dispositivo sea menor o igual a 800 px. +
+ +## Tests +
+ +```yml +tests: + - text: Su elemento p debe tener el font-size de font-size de 10 px cuando la height del dispositivo sea menor o igual a 800 px. + testString: 'assert($("p").css("font-size") == "10px", "Your p element should have the font-size of 10px when the device height is less than or equal to 800px.");' + - text: Declare una consulta @media para dispositivos con una height menor o igual a 800px. + testString: 'assert(code.match(/@media\s*?\(\s*?max-height\s*?:\s*?800px\s*?\)/g), "Declare a @media query for devices with a height less than or equal to 800px.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis tempus massa. Aenean erat nisl, gravida vel vestibulum cursus, interdum sit amet lectus. Sed sit amet quam nibh. Suspendisse quis tincidunt nulla. In hac habitasse platea dictumst. Ut sit amet pretium nisl. Vivamus vel mi sem. Aenean sit amet consectetur sem. Suspendisse pretium, purus et gravida consequat, nunc ligula ultricies diam, at aliquet velit libero a dui.

+``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-an-image-responsive.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-an-image-responsive.spanish.md new file mode 100644 index 0000000000..293a9ccdaa --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-an-image-responsive.spanish.md @@ -0,0 +1,64 @@ +--- +id: 587d78b1367417b2b2512b09 +title: Make an Image Responsive +localeTitle: Hacer una imagen receptiva +challengeType: 0 +videoUrl: '' +--- + +## Description +
+Hacer que las imágenes respondan con CSS es realmente muy simple. En lugar de aplicar un ancho absoluto a un elemento: +img { width: 720px; } +Puedes usar: +
img {
  max-width: 100%;
  display: block;
  height: auto;
}
+La propiedad de max-width del 100% ajusta la imagen para que se ajuste al ancho de su contenedor, pero la imagen no se estirará más que su ancho original. La configuración de la propiedad de display para bloquear cambia la imagen de un elemento en línea (su valor predeterminado) a un elemento de bloque en su propia línea. La propiedad de height de auto mantiene la relación de aspecto original de la imagen. +
+ +## Instructions +
+Agregue reglas de estilo para la etiqueta img para que responda al tamaño de su contenedor. Debe mostrarse como un elemento de nivel de bloque, debe ajustarse a todo el ancho de su contenedor sin estirarlo y debe mantener su relación de aspecto original. +
+ +## Tests +
+ +```yml +tests: + - text: Su etiqueta img debe tener un max-width establecido al 100%. + testString: 'assert(code.match(/max-width:\s*?100%;/g), "Your img tag should have a max-width set to 100%.");' + - text: Su etiqueta img debe tener un conjunto de display para bloquear. + testString: 'assert($("img").css("display") == "block", "Your img tag should have a display set to block.");' + - text: Tu etiqueta img debe tener una height establecida en auto. + testString: 'assert(code.match(/height:\s*?auto;/g), "Your img tag should have a height set to auto.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +freeCodeCamp stickers set +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-typography-responsive.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-typography-responsive.spanish.md new file mode 100644 index 0000000000..567084f19b --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/make-typography-responsive.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d78b1367417b2b2512b0c +title: Make Typography Responsive +localeTitle: Hacer que la tipografía responda +challengeType: 0 +videoUrl: '' +--- + +## Description +
+En lugar de usar em o px para px tamaño del texto, puede usar unidades de vista para tipografía sensible. Las unidades de vista, como los porcentajes, son unidades relativas, pero se basan en elementos diferentes. Las unidades de la ventana gráfica son relativas a las dimensiones de la ventana gráfica (ancho o alto) de un dispositivo, y los porcentajes son relativos al tamaño del elemento contenedor primario. +Las cuatro unidades de viewport diferentes son: + +
+ +## Instructions +
+Establezca el width de la etiqueta h2 en el 80% del ancho de la ventana gráfica y el width del párrafo como el 75% de la dimensión más pequeña de la ventana gráfica. +
+ +## Tests +
+ +```yml +tests: + - text: Su etiqueta h2 debe tener un width de 80vw. + testString: 'assert(code.match(/h2\s*?{\s*?width:\s*?80vw;\s*?}/g), "Your h2 tag should have a width of 80vw.");' + - text: Su etiqueta p debe tener un width de 75vmin. + testString: 'assert(code.match(/p\s*?{\s*?width:\s*?75vmin;\s*?}/g), "Your p tag should have a width of 75vmin.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +

Importantus Ipsum

+

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis tempus massa. Aenean erat nisl, gravida vel vestibulum cursus, interdum sit amet lectus. Sed sit amet quam nibh. Suspendisse quis tincidunt nulla. In hac habitasse platea dictumst. Ut sit amet pretium nisl. Vivamus vel mi sem. Aenean sit amet consectetur sem. Suspendisse pretium, purus et gravida consequat, nunc ligula ultricies diam, at aliquet velit libero a dui.

+``` + +
+ + + +
+ +## Solution +
+ + +```js +var code = "h2 {width: 80vw;} p {width: 75vmin;}" +``` + +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/use-a-retina-image-for-higher-resolution-displays.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/use-a-retina-image-for-higher-resolution-displays.spanish.md new file mode 100644 index 0000000000..66723ecfde --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-principles/use-a-retina-image-for-higher-resolution-displays.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d78b1367417b2b2512b0a +title: Use a Retina Image for Higher Resolution Displays +localeTitle: Utilice una imagen de retina para pantallas de mayor resolución +challengeType: 0 +videoUrl: '' +--- + +## Description +
+La forma más sencilla de hacer que sus imágenes aparezcan como "retina" (y optimizarlas para las pantallas de retina) es definir sus valores de width y height como solo la mitad de lo que es el archivo original. +Aquí hay un ejemplo de una imagen que solo usa la mitad de la altura y el ancho originales: +
<style>
  img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
+
+ +## Instructions +
+Establezca el width y el height de la etiqueta img en la mitad de sus valores originales. En este caso, tanto la height original como el width original son 200 px. +
+ +## Tests +
+ +```yml +tests: + - text: Su etiqueta img debe tener un width de 100 píxeles. + testString: 'assert($("img").css("width") == "100px", "Your img tag should have a width of 100 pixels.");' + - text: Su etiqueta img debe tener una height de 100 píxeles. + testString: 'assert($("img").css("height") == "100px", "Your img tag should have a height of 100 pixels.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```html + + +freeCodeCamp sticker that says 'Because CamperBot Cares' +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.spanish.md new file mode 100644 index 0000000000..9898141448 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-personal-portfolio-webpage.spanish.md @@ -0,0 +1,56 @@ +--- +id: bd7158d8c242eddfaeb5bd13 +title: Build a Personal Portfolio Webpage +localeTitle: Crear una página web de cartera personal +isRequired: true +challengeType: 3 +--- + +## Description +
+Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/zNBOYG . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puedes usar HTML, JavaScript y CSS para completar este proyecto. Se recomienda CSS simple porque eso es lo que las lecciones han cubierto hasta ahora y debe obtener algo de práctica con CSS simple. Puede utilizar Bootstrap o SASS si lo desea. No se recomiendan tecnologías adicionales (solo por ejemplo, jQuery, React, Angular o Vue) para este proyecto, y su uso es bajo su propio riesgo. Otros proyectos te darán la oportunidad de trabajar con diferentes pilas de tecnología como React. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Mi cartera debe tener una sección de bienvenida con una identificación de welcome-section de welcome-section . +Historia de usuario # 2: La sección de bienvenida debe tener un elemento h1 que contenga texto. +Historia de usuario # 3: Mi cartera debe tener una sección de proyectos con una identificación de projects . +Historia de usuario # 4: La sección de proyectos debe contener al menos un elemento con una clase de project-tile para contener un proyecto. +Historia de usuario # 5: La sección de proyectos debe contener al menos un enlace a un proyecto. +Historia de usuario # 6: Mi cartera debe tener una barra de navegación con un ID de navbar de navbar . +Historia de usuario n. ° 7: La barra de navegación debe contener al menos un enlace en el que pueda hacer clic para navegar a diferentes secciones de la página. +Historia del usuario n. ° 8: Mi cartera debe tener un enlace con un ID de profile-link , que abre mi perfil de GitHub o FCC en una nueva pestaña. +Historia de usuario # 9: Mi cartera debe tener al menos una consulta de medios. +Historia de usuario # 10: La altura de la sección de bienvenida debe ser igual a la altura de la ventana gráfica. +Historia de usuario # 11: La barra de navegación siempre debe estar en la parte superior de la ventana gráfica. +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: [] + +``` + +
+ +## Challenge Seed +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.spanish.md new file mode 100644 index 0000000000..0097ae2a8f --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-product-landing-page.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d78af367417b2b2512b04 +title: Build a Product Landing Page +localeTitle: Construir una página de inicio de producto +isRequired: true +challengeType: 3 +--- + +## Description +
+Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/RKRbwL . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puedes usar HTML, JavaScript y CSS para completar este proyecto. Se recomienda CSS simple porque eso es lo que las lecciones han cubierto hasta ahora y debe obtener algo de práctica con CSS simple. Puede utilizar Bootstrap o SASS si lo desea. No se recomiendan tecnologías adicionales (solo por ejemplo, jQuery, React, Angular o Vue) para este proyecto, y su uso es bajo su propio riesgo. Otros proyectos te darán la oportunidad de trabajar con diferentes pilas de tecnología como React. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: La página de destino de mi producto debe tener un elemento de header con un id="header" . +Historia de usuario n. ° 2: Puedo ver una imagen dentro del elemento del header con el correspondiente id="header-img" . Un logo de empresa sería una buena imagen aquí. +Historia de usuario # 3: Dentro del elemento #header puedo ver un elemento de nav con una id="nav-bar" correspondiente id="nav-bar" . +Historia de usuario # 4: Puedo ver al menos tres elementos seleccionables dentro del elemento nav , cada uno con la clase nav-link . +Historia de usuario # 5: Cuando hago clic en un botón .nav-link en el elemento de nav , me lleva a la sección correspondiente de la página de destino. +Historia de usuario n. ° 6: Puedo ver un video de un producto incorporado con id="video" . +Historia de usuario n. ° 7: Mi página de destino tiene un elemento de form con una id="form" correspondiente id="form" . +Historia de usuario # 8: Dentro del formulario, hay un campo de input con id="email" donde puedo ingresar una dirección de correo electrónico. +Historia de usuario n. ° 9: El campo de entrada #email debe tener un texto de marcador de posición para que el usuario sepa para qué sirve el campo. +Historia de usuario # 10: el campo de entrada #email usa validación HTML5 para confirmar que el texto ingresado es una dirección de correo electrónico. +Historia de usuario # 11: Dentro del formulario, hay una input envío con un id="submit" correspondiente id="submit" . +Historia del usuario # 12: Cuando hago clic en el elemento #submit , el correo electrónico se envía a una página estática (use esta URL simulada: https://www.freecodecamp.com/email-submit ) que confirma que se ingresó la dirección de correo electrónico y que publicó con éxito. +Historia de usuario n. ° 13: la barra de navegación siempre debe estar en la parte superior de la ventana gráfica. +Historia de usuario n. ° 14: La página de inicio de mi producto debe tener al menos una consulta de medios. +Historia de usuario # 15: La página de inicio de mi producto debe utilizar CSS flexbox al menos una vez. +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: [] + +``` + +
+ +## Challenge Seed +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.spanish.md new file mode 100644 index 0000000000..d63c09a126 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-survey-form.spanish.md @@ -0,0 +1,61 @@ +--- +id: 587d78af367417b2b2512b03 +title: Build a Survey Form +localeTitle: Crear un formulario de encuesta +isRequired: true +challengeType: 3 +--- + +## Description +
+Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/VPaoNP . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puedes usar HTML, JavaScript y CSS para completar este proyecto. Se recomienda CSS simple porque eso es lo que las lecciones han cubierto hasta ahora y debe obtener algo de práctica con CSS simple. Puede utilizar Bootstrap o SASS si lo desea. No se recomiendan tecnologías adicionales (solo por ejemplo, jQuery, React, Angular o Vue) para este proyecto, y su uso es bajo su propio riesgo. Otros proyectos te darán la oportunidad de trabajar con diferentes pilas de tecnología como React. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: puedo ver un título con id="title" en texto de tamaño H1. +Historia de usuario n. ° 2: Puedo ver una breve explicación con id="description" en texto de tamaño P. +Historia de usuario n. ° 3: Puedo ver un form con id="survey-form" . +Historia de usuario n. ° 4: Dentro del elemento del formulario, debo ingresar mi nombre en un campo con id="name" . +Historia de usuario # 5: Dentro del elemento del formulario, debo ingresar un correo electrónico en un campo con id="email" . +Historia de usuario n. ° 6: Si ingreso un correo electrónico que no tiene el formato correcto, veré un error de validación de HTML5. +Historia de usuario # 7: Dentro del formulario, puedo ingresar un número en un campo con id="number" . +Historia de usuario n. ° 8: Si ingreso números que no son números en la entrada del número, veré un error de validación de HTML5. +Historia de usuario n. ° 9: si ingreso números fuera del rango de entrada de números, que están definidos por los atributos min y max , veré un error de validación de HTML5. +Historia de usuario # 10: Para los campos de ingreso de nombre, correo electrónico y número dentro del formulario, puedo ver las etiquetas correspondientes que describen el propósito de cada campo con los siguientes id="name-label" : id="name-label" , id="email-label" , y id="number-label" . +Historia del usuario n. ° 11: Para los campos de ingreso de nombre, correo electrónico y número, puedo ver el texto del marcador de posición que me da una descripción o instrucciones para cada campo. +Historia del usuario # 12: Dentro del elemento del formulario, puedo seleccionar una opción de un menú desplegable que tiene un id="dropdown" correspondiente id="dropdown" . +Historia de usuario # 13: Dentro del elemento del formulario, puedo seleccionar un campo de uno o más grupos de botones de radio. Cada grupo debe agruparse usando el atributo de name . +Historia del usuario n. ° 14: Dentro del elemento del formulario, puedo seleccionar varios campos de una serie de casillas de verificación, cada una de las cuales debe tener un atributo de value . +Historia de usuario # 15: Dentro del elemento del formulario, me presentan un área de textarea al final para comentarios adicionales. +Historia de usuario # 16: Dentro del elemento del formulario, se me presenta un botón con id="submit" para enviar todas mis entradas. +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: [] + +``` + +
+ +## Challenge Seed +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.spanish.md new file mode 100644 index 0000000000..ea0c600123 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-technical-documentation-page.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d78b0367417b2b2512b05 +title: Build a Technical Documentation Page +localeTitle: Construir una página de documentación técnica +isRequired: true +challengeType: 3 +--- + +## Description +
+Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/NdrKKL . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puedes usar HTML, JavaScript y CSS para completar este proyecto. Se recomienda CSS simple porque eso es lo que las lecciones han cubierto hasta ahora y debe obtener algo de práctica con CSS simple. Puede utilizar Bootstrap o SASS si lo desea. No se recomiendan tecnologías adicionales (solo por ejemplo, jQuery, React, Angular o Vue) para este proyecto, y su uso es bajo su propio riesgo. Otros proyectos te darán la oportunidad de trabajar con diferentes pilas de tecnología como React. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Puedo ver un elemento main con un id="main-doc" correspondiente id="main-doc" , que contiene el contenido principal de la página (documentación técnica). +Historia de usuario # 2: Dentro del elemento #main-doc , puedo ver varios elementos de section , cada uno con una clase de main-section . Debe haber un mínimo de 5. +Historia de usuario # 3: El primer elemento dentro de cada .main-section debe ser un elemento de header que contenga texto que describa el tema de esa sección. +Historia de usuario n. ° 4: Cada elemento de section con la clase de main-section también debe tener un ID que se corresponda con el texto de cada header contenido en él. Cualquier espacio debe reemplazarse con guiones bajos (por ejemplo, la section que contiene el encabezado "Javascript y Java" debe tener una id="Javascript_and_Java" correspondiente id="Javascript_and_Java" ). +usuario Historia # 5: Los .main-section elementos deben contener al menos 10 p total de elementos (no cada uno). +Historia de usuario n. ° 6: Los .main-section deben contener al menos 5 elementos de code total (no cada uno). +usuario Historia # 7: Los .main-section elementos deben contener al menos 5 li total de los artículos (no cada uno). +Historia de usuario n. ° 8: Puedo ver un elemento de nav con una id="navbar" correspondiente id="navbar" . +Historia de usuario # 9: El elemento de la barra de navegación debe contener un elemento de header que contenga texto que describa el tema de la documentación técnica. +Historia de usuario # 10: Además, la barra de navegación debe contener elementos del enlace ( a ) con la clase de nav-link de nav-link . Debe haber uno para cada elemento con la clase main-section . +Historia de usuario # 11: El elemento de header en la barra de navegación debe aparecer antes que cualquier elemento de enlace ( a ) en la barra de navegación. +Historia de usuario n. ° 12: Cada elemento con la clase de nav-link de nav-link debe contener texto que corresponda al texto del header dentro de cada section (por ejemplo, si tiene una sección / encabezado de "Hola mundo", su barra de navegación debe tener un elemento que contenga el texto "Hola mundo"). +Historia de usuario n. ° 13: cuando hago clic en un elemento de la barra de navegación, la página debe navegar a la sección correspondiente del elemento main-doc (por ejemplo, si hago clic en un elemento de nav-link que contiene el texto "Hola mundo", la página navega a un elemento de section que tiene ese id y contiene el header correspondiente. +Historia del usuario n. ° 14: En dispositivos de tamaño normal (computadoras portátiles, computadoras de escritorio), el elemento con id="navbar" debe mostrar en el lado izquierdo de la pantalla y el usuario siempre debe estar visible. +Historia del usuario n. ° 15: La página Mi documentación técnica debe usar al menos una consulta de medios. +Puede construir su proyecto por medio de este bolígrafo de CodePen . O bien, puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que le guste: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su proyecto de trabajo con todas las pruebas aprobadas. +Recuerde usar el método Read-Search-Ask si te quedas atascado. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: [] + +``` + +
+ +## Challenge Seed +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.spanish.md b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.spanish.md new file mode 100644 index 0000000000..7692131014 --- /dev/null +++ b/curriculum/challenges/spanish/01-responsive-web-design/responsive-web-design-projects/build-a-tribute-page.spanish.md @@ -0,0 +1,54 @@ +--- +id: bd7158d8c442eddfaeb5bd18 +title: Build a Tribute Page +localeTitle: Construir una página de tributo +isRequired: true +challengeType: 3 +--- + +## Description +
+Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/zNqgVx . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puedes usar HTML, JavaScript y CSS para completar este proyecto. Se recomienda CSS simple porque eso es lo que las lecciones han cubierto hasta ahora y debe obtener algo de práctica con CSS simple. Puede utilizar Bootstrap o SASS si lo desea. No se recomiendan tecnologías adicionales (solo por ejemplo, jQuery, React, Angular o Vue) para este proyecto, y su uso es bajo su propio riesgo. Otros proyectos te darán la oportunidad de trabajar con diferentes pilas de tecnología como React. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Mi página de tributo debe tener un elemento con una id="main" correspondiente id="main" , que contiene todos los demás elementos. +Historia de usuario # 2: Debería ver un elemento con un id="title" correspondiente id="title" , que contiene una cadena (es decir, texto) que describe el tema de la página de tributo (por ejemplo, "Dr. Norman Borlaug"). +Historia de usuario n. ° 3: Debería ver un elemento div con un id="img-div" correspondiente id="img-div" . +Historia de usuario # 4: Dentro del elemento img-div , debería ver un elemento img con una id="image" correspondiente id="image" . +Historia de usuario # 5: Dentro del elemento img-div , debería ver un elemento con un id="img-caption" correspondiente id="img-caption" que contiene contenido textual que describe la imagen que se muestra en img-div . +Historia de usuario # 6: Debería ver un elemento con una id="tribute-info" correspondiente id="tribute-info" , que contiene contenido textual que describe el tema de la página de tributo. +Usuario Historia # 7: Debería ver una a elemento con un correspondiente id="tribute-link" , que une a un sitio externo que contiene información adicional sobre el tema de la página de tributo. SUGERENCIA: debe asignar a su elemento un atributo de target y configurarlo en _blank para que su enlace se abra en una nueva pestaña (es decir, target="_blank" ). +Historia de usuario n. ° 8: El elemento img debe redimensionarse responsivamente, en relación con el ancho de su elemento principal, sin exceder su tamaño original. +Historia de usuario # 9: El elemento img debe estar centrado dentro de su elemento principal. +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en el entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js . +Una vez que haya terminado, envíe la URL a su proyecto de trabajo con todas las pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: [] + +``` + +
+ +## Challenge Seed +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who.spanish.md new file mode 100644 index 0000000000..6812f3bcda --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who.spanish.md @@ -0,0 +1,83 @@ +--- +id: a77dbc43c33f39daa4429b4f +title: Boo who +localeTitle: Boo quien +isRequired: true +challengeType: 5 +--- + +## Description +
+Compruebe si un valor está clasificado como un primitivo booleano. Devuelve verdadero o falso. +Los primitivos booleanos son verdaderos y falsos. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: booWho(true) debe devolver true. + testString: 'assert.strictEqual(booWho(true), true, "booWho(true) should return true.");' + - text: booWho(false) debe devolver verdadero. + testString: 'assert.strictEqual(booWho(false), true, "booWho(false) should return true.");' + - text: ' booWho([1, 2, 3]) debe devolver falso.' + testString: 'assert.strictEqual(booWho([1, 2, 3]), false, "booWho([1, 2, 3]) should return false.");' + - text: ' booWho([].slice) debe devolver falso.' + testString: 'assert.strictEqual(booWho([].slice), false, "booWho([].slice) should return false.");' + - text: ' booWho({ "a": 1 }) debe devolver falso.' + testString: 'assert.strictEqual(booWho({ "a": 1 }), false, "booWho({ "a": 1 }) should return false.");' + - text: booWho(1) debe devolver falso. + testString: 'assert.strictEqual(booWho(1), false, "booWho(1) should return false.");' + - text: booWho(NaN) debe devolver falso. + testString: 'assert.strictEqual(booWho(NaN), false, "booWho(NaN) should return false.");' + - text: booWho("a") debe devolver falso. + testString: 'assert.strictEqual(booWho("a"), false, "booWho("a") should return false.");' + - text: booWho("true") debería devolver falso. + testString: 'assert.strictEqual(booWho("true"), false, "booWho("true") should return false.");' + - text: booWho("false") debe devolver false. + testString: 'assert.strictEqual(booWho("false"), false, "booWho("false") should return false.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function booWho(bool) { + // What is the new fad diet for ghost developers? The Boolean. + return bool; +} + +booWho(null); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function booWho(bool) { + return typeof bool === "boolean"; +} + +booWho(null); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey.spanish.md new file mode 100644 index 0000000000..78cbcaef23 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey.spanish.md @@ -0,0 +1,83 @@ +--- +id: a9bd25c716030ec90084d8a1 +title: Chunky Monkey +localeTitle: Mono grueso +isRequired: true +challengeType: 5 +--- + +## Description +
+Escriba una función que divida una matriz (primer argumento) en grupos de la longitud del size (segundo argumento) y los devuelva como una matriz bidimensional. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' chunkArrayInGroups(["a", "b", "c", "d"], 2) debe devolver [["a", "b"], ["c", "d"]] .' + testString: 'assert.deepEqual(chunkArrayInGroups(["a", "b", "c", "d"], 2), [["a", "b"], ["c", "d"]], "chunkArrayInGroups(["a", "b", "c", "d"], 2) should return [["a", "b"], ["c", "d"]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) debe devolver [[0, 1, 2], [3, 4, 5]] .' + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [[0, 1, 2], [3, 4, 5]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3) should return [[0, 1, 2], [3, 4, 5]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) debe devolver [[0, 1], [2, 3], [4, 5]] .' + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [[0, 1], [2, 3], [4, 5]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2) should return [[0, 1], [2, 3], [4, 5]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4) debe devolver [[0, 1, 2, 3], [4, 5]] .' + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [[0, 1, 2, 3], [4, 5]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4) should return [[0, 1, 2, 3], [4, 5]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) debe devolver [[0, 1, 2], [3, 4, 5], [6]] .' + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [[0, 1, 2], [3, 4, 5], [6]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3) should return [[0, 1, 2], [3, 4, 5], [6]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) debe devolver [[0, 1, 2, 3], [4, 5, 6, 7], [8]] . ' + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [[0, 1, 2, 3], [4, 5, 6, 7], [8]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4) should return [[0, 1, 2, 3], [4, 5, 6, 7], [8]].");' + - text: ' chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) debe devolver [[0, 1], [2, 3], [4, 5], [6, 7], [8]] . + testString: 'assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [[0, 1], [2, 3], [4, 5], [6, 7], [8]], "chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2) should return [[0, 1], [2, 3], [4, 5], [6, 7], [8]].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function chunkArrayInGroups(arr, size) { + // Break it up. + return arr; +} + +chunkArrayInGroups(["a", "b", "c", "d"], 2); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function chunkArrayInGroups(arr, size) { + let out = []; + + for (let i = 0; i < arr.length; i += size) { + out.push(arr.slice(i, i + size)); + } + + return out; +} + +chunkArrayInGroups(["a", "b", "c", "d"], 2); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending.spanish.md new file mode 100644 index 0000000000..e86fd561f5 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending.spanish.md @@ -0,0 +1,87 @@ +--- +id: acda2fb1324d9b0fa741e6b5 +title: Confirm the Ending +localeTitle: Confirmar el final +isRequired: true +challengeType: 5 +--- + +## Description +
+Compruebe si una cadena (primer argumento, str ) termina con la cadena de destino dada (segundo argumento, target ). +Este desafío se puede resolver con el método .endsWith() , que se introdujo en ES2015. Pero para el propósito de este desafío, nos gustaría que utilices uno de los métodos de subcadena de JavaScript. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' confirmEnding("Bastian", "n") debe devolver verdadero.' + testString: 'assert(confirmEnding("Bastian", "n") === true, "confirmEnding("Bastian", "n") should return true.");' + - text: ' confirmEnding("Congratulation", "on") debe devolver verdadero.' + testString: 'assert(confirmEnding("Congratulation", "on") === true, "confirmEnding("Congratulation", "on") should return true.");' + - text: ' confirmEnding("Connor", "n") debe devolver falso.' + testString: 'assert(confirmEnding("Connor", "n") === false, "confirmEnding("Connor", "n") should return false.");' + - text: ' confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") debe devolver falso. + testString: 'assert(confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") === false, "confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.");' + - text: ' confirmEnding("He has to give me a new name", "name") debe devolver verdadero.' + testString: 'assert(confirmEnding("He has to give me a new name", "name") === true, "confirmEnding("He has to give me a new name", "name") should return true.");' + - text: ' confirmEnding("Open sesame", "same") debe devolver verdadero.' + testString: 'assert(confirmEnding("Open sesame", "same") === true, "confirmEnding("Open sesame", "same") should return true.");' + - text: ' confirmEnding("Open sesame", "pen") debe devolver falso. + testString: 'assert(confirmEnding("Open sesame", "pen") === false, "confirmEnding("Open sesame", "pen") should return false.");' + - text: ' confirmEnding("Open sesame", "game") debe devolver falso. + testString: 'assert(confirmEnding("Open sesame", "game") === false, "confirmEnding("Open sesame", "game") should return false.");' + - text: ' confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") debería devolver el valor falso ". + testString: 'assert(confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") === false, "confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") should return false.");' + - text: ' confirmEnding("Abstraction", "action") debe devolver verdadero.' + testString: 'assert(confirmEnding("Abstraction", "action") === true, "confirmEnding("Abstraction", "action") should return true.");' + - text: No use el método .endsWith() para resolver el desafío. + testString: 'assert(!(/\.endsWith\(.*?\)\s*?;?/.test(code)) && !(/\["endsWith"\]/.test(code)), "Do not use the built-in method .endsWith() to solve the challenge.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function confirmEnding(str, target) { + // "Never give up and good luck will find you." + // -- Falcor + return str; +} + +confirmEnding("Bastian", "n"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function confirmEnding(str, target) { + return str.substring(str.length - target.length) === target; +} + +confirmEnding("Bastian", "n"); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit.spanish.md new file mode 100644 index 0000000000..09999df803 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit.spanish.md @@ -0,0 +1,78 @@ +--- +id: 56533eb9ac21ba0edf2244b3 +title: Convert Celsius to Fahrenheit +localeTitle: Convertir Celsius a Fahrenheit +challengeType: 1 +isRequired: true +--- + +## Description +
+El algoritmo para convertir de Celsius a Fahrenheit es la temperatura en grados Celsius 9/5 , más 32 . +Se le da una variable celsius representa una temperatura en grados centígrados. Use la variable fahrenheit ya definida y asígnele la temperatura Fahrenheit equivalente a la temperatura Celsius dada. Use el algoritmo mencionado anteriormente para ayudar a convertir la temperatura en grados Celsius a Fahrenheit. +No se preocupe demasiado por la función y las declaraciones de devolución, ya que se cubrirán en futuros desafíos. Por ahora, solo utiliza operadores que ya hayas aprendido. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: convertToF(0) debe devolver un número + testString: 'assert(typeof convertToF(0) === "number", "convertToF(0) should return a number");' + - text: convertToF(-30) debe devolver un valor de -22 + testString: 'assert(convertToF(-30) === -22, "convertToF(-30) should return a value of -22");' + - text: convertToF(-10) debe devolver un valor de 14 + testString: 'assert(convertToF(-10) === 14, "convertToF(-10) should return a value of 14");' + - text: convertToF(0) debe devolver un valor de 32 + testString: 'assert(convertToF(0) === 32, "convertToF(0) should return a value of 32");' + - text: convertToF(20) debe devolver un valor de 68 + testString: 'assert(convertToF(20) === 68, "convertToF(20) should return a value of 68");' + - text: convertToF(30) debe devolver un valor de 86 + testString: 'assert(convertToF(30) === 86, "convertToF(30) should return a value of 86");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function convertToF(celsius) { + let fahrenheit; + return fahrenheit; +} + +convertToF(30); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function convertToF(celsius) { + let fahrenheit = celsius * 9/5 + 32; + + return fahrenheit; +} + +convertToF(30); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number.spanish.md new file mode 100644 index 0000000000..00adf685f4 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number.spanish.md @@ -0,0 +1,76 @@ +--- +id: a302f7aae1aa3152a5b413bc +title: Factorialize a Number +localeTitle: Factorializar un número +isRequired: true +challengeType: 5 +--- + +## Description +
+Devuelve el factorial del entero proporcionado. +Si el entero se representa con la letra n, un factorial es el producto de todos los enteros positivos menores o iguales a n. +factoriales a menudo se representan con la notación abreviada n! +Por ejemplo: 5! = 1 * 2 * 3 * 4 * 5 = 120 +Solo se proporcionarán a la función números enteros mayores o iguales a cero. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: factorialize(5) debe devolver un número. + testString: 'assert(typeof factorialize(5) === "number", "factorialize(5) should return a number.");' + - text: factorialize(5) debe devolver 120. + testString: 'assert(factorialize(5) === 120, "factorialize(5) should return 120.");' + - text: factorialize(10) debe devolver 3628800. + testString: 'assert(factorialize(10) === 3628800, "factorialize(10) should return 3628800.");' + - text: factorialize(20) debe devolver 2432902008176640000. + testString: 'assert(factorialize(20) === 2432902008176640000, "factorialize(20) should return 2432902008176640000.");' + - text: factorialize(0) debe devolver 1. + testString: 'assert(factorialize(0) === 1, "factorialize(0) should return 1.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function factorialize(num) { + return num; +} + +factorialize(5); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function factorialize(num) { + return num < 1 ? 1 : num * factorialize(num - 1); +} + +factorialize(5); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer.spanish.md new file mode 100644 index 0000000000..5eba2d8154 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer.spanish.md @@ -0,0 +1,73 @@ +--- +id: adf08ec01beb4f99fc7a68f2 +title: Falsy Bouncer +localeTitle: Falsy Bouncer +isRequired: true +challengeType: 5 +--- + +## Description +
+Eliminar todos los valores falsos de una matriz. +valores de false en JavaScript son false , null , 0 , "" , undefined y NaN . +Sugerencia: intente convertir cada valor a un booleano. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' bouncer([7, "ate", "", false, 9]) debe devolver [7, "ate", 9] .' + testString: 'assert.deepEqual(bouncer([7, "ate", "", false, 9]), [7, "ate", 9], "bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9].");' + - text: ' bouncer(["a", "b", "c"]) debe devolver ["a", "b", "c"] .' + testString: 'assert.deepEqual(bouncer(["a", "b", "c"]), ["a", "b", "c"], "bouncer(["a", "b", "c"]) should return ["a", "b", "c"].");' + - text: ' bouncer([false, null, 0, NaN, undefined, ""]) debe devolver [] .' + testString: 'assert.deepEqual(bouncer([false, null, 0, NaN, undefined, ""]), [], "bouncer([false, null, 0, NaN, undefined, ""]) should return [].");' + - text: ' bouncer([1, null, NaN, 2, undefined]) debe devolver [1, 2] .' + testString: 'assert.deepEqual(bouncer([1, null, NaN, 2, undefined]), [1, 2], "bouncer([1, null, NaN, 2, undefined]) should return [1, 2].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function bouncer(arr) { + // Don't show a false ID to this bouncer. + return arr; +} + +bouncer([7, "ate", "", false, 9]); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function bouncer(arr) { + return arr.filter(e => e); +} + +bouncer([7, "ate", "", false, 9]); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string.spanish.md new file mode 100644 index 0000000000..4abd40f064 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string.spanish.md @@ -0,0 +1,75 @@ +--- +id: a26cbbe9ad8655a977e1ceb5 +title: Find the Longest Word in a String +localeTitle: Encuentra la palabra más larga en una cadena +isRequired: true +challengeType: 5 +--- + +## Description +
+Devuelve la longitud de la palabra más larga en la oración provista. +Tu respuesta debe ser un número. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: findLongestWordLength("The quick brown fox jumped over the lazy dog") debería devolver un número. + testString: 'assert(typeof findLongestWordLength("The quick brown fox jumped over the lazy dog") === "number", "findLongestWordLength("The quick brown fox jumped over the lazy dog") should return a number.");' + - text: findLongestWordLength("The quick brown fox jumped over the lazy dog") debería devolver 6. + testString: 'assert(findLongestWordLength("The quick brown fox jumped over the lazy dog") === 6, "findLongestWordLength("The quick brown fox jumped over the lazy dog") should return 6.");' + - text: findLongestWordLength("May the force be with you") debe devolver 5. + testString: 'assert(findLongestWordLength("May the force be with you") === 5, "findLongestWordLength("May the force be with you") should return 5.");' + - text: findLongestWordLength("Google do a barrel roll") debe devolver 6. + testString: 'assert(findLongestWordLength("Google do a barrel roll") === 6, "findLongestWordLength("Google do a barrel roll") should return 6.");' + - text: findLongestWordLength("What is the average airspeed velocity of an unladen swallow") debe devolver 8. + testString: 'assert(findLongestWordLength("What is the average airspeed velocity of an unladen swallow") === 8, "findLongestWordLength("What is the average airspeed velocity of an unladen swallow") should return 8.");' + - text: findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") debería devolver 19. + testString: 'assert(findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") === 19, "findLongestWordLength("What if we try a super-long word such as otorhinolaryngology") should return 19.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function findLongestWordLength(str) { + return str.length; +} + +findLongestWordLength("The quick brown fox jumped over the lazy dog"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function findLongestWordLength(str) { + return str.split(' ').sort((a, b) => b.length - a.length)[0].length; +} + +findLongestWordLength("The quick brown fox jumped over the lazy dog"); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers.spanish.md new file mode 100644 index 0000000000..6164b8cda9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/finders-keepers.spanish.md @@ -0,0 +1,76 @@ +--- +id: a6e40f1041b06c996f7b2406 +title: Finders Keepers +localeTitle: Buscadores guardianes +isRequired: true +challengeType: 5 +--- + +## Description +
+Cree una función que examine una matriz (primer argumento) y devuelva el primer elemento de la matriz que pase una prueba de verdad (segundo argumento). Si ningún elemento pasa la prueba, devuelva indefinido. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) debe devolver 8.' + testString: 'assert.strictEqual(findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }), 8, "findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; }) should return 8.");' + - text: ' findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) debe devolver undefined.' + testString: 'assert.strictEqual(findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }), undefined, "findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; }) should return undefined.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function findElement(arr, func) { + let num = 0; + return num; +} + +findElement([1, 2, 3, 4], num => num % 2 === 0); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function findElement(arr, func) { + let num; + + arr.some(e => { + if (func(e)) { + num = e; + return true; + } + }); + + return num; +} + +findElement([1, 2, 3, 4], num => num % 2 === 0); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations.spanish.md new file mode 100644 index 0000000000..9cf69fad9c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations.spanish.md @@ -0,0 +1,87 @@ +--- +id: af2170cad53daa0770fabdea +title: Mutations +localeTitle: Mutaciones +isRequired: true +challengeType: 5 +--- + +## Description +
+Devuelva verdadero si la cadena en el primer elemento de la matriz contiene todas las letras de la cadena en el segundo elemento de la matriz. +Por ejemplo, ["hello", "Hello"] , debería devolver verdadero porque todas las letras en la segunda cadena están presentes en el primer caso, ignorando el caso. +Los argumentos ["hello", "hey"] deben devolver falso porque la cadena "hola" no contiene una "y". +Por último, ["Alien", "line"] , debe devolver verdadero porque todas las letras en "line" están presentes en "Alien". +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' mutation(["hello", "hey"]) debe devolver falso.' + testString: 'assert(mutation(["hello", "hey"]) === false, "mutation(["hello", "hey"]) should return false.");' + - text: ' mutation(["hello", "Hello"]) debe devolver verdadero.' + testString: 'assert(mutation(["hello", "Hello"]) === true, "mutation(["hello", "Hello"]) should return true.");' + - text: ' mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]) debe devolver verdadero.' + testString: 'assert(mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]) === true, "mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"]) should return true.");' + - text: 'la mutation(["Mary", "Army"]) debería devolver la verdad.' + testString: 'assert(mutation(["Mary", "Army"]) === true, "mutation(["Mary", "Army"]) should return true.");' + - text: 'la mutation(["Mary", "Aarmy"]) debe devolver la verdad.' + testString: 'assert(mutation(["Mary", "Aarmy"]) === true, "mutation(["Mary", "Aarmy"]) should return true.");' + - text: ' mutation(["Alien", "line"]) debe devolver true.' + testString: 'assert(mutation(["Alien", "line"]) === true, "mutation(["Alien", "line"]) should return true.");' + - text: ' mutation(["floor", "for"]) debe devolver verdadero.' + testString: 'assert(mutation(["floor", "for"]) === true, "mutation(["floor", "for"]) should return true.");' + - text: ' mutation(["hello", "neo"]) debe devolver falso.' + testString: 'assert(mutation(["hello", "neo"]) === false, "mutation(["hello", "neo"]) should return false.");' + - text: ' mutation(["voodoo", "no"]) debe devolver falso.' + testString: 'assert(mutation(["voodoo", "no"]) === false, "mutation(["voodoo", "no"]) should return false.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function mutation(arr) { + return arr; +} + +mutation(["hello", "hey"]); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function mutation(arr) { + let hash = Object.create(null); + + arr[0].toLowerCase().split('').forEach(c => hash[c] = true); + + return !arr[1].toLowerCase().split('').filter(c => !hash[c]).length; +} + +mutation(["hello", "hey"]); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string.spanish.md new file mode 100644 index 0000000000..340aa8ae42 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string.spanish.md @@ -0,0 +1,78 @@ +--- +id: afcc8d540bea9ea2669306b6 +title: Repeat a String Repeat a String +localeTitle: Repetir una cadena Repetir una cadena +isRequired: true +challengeType: 5 +--- + +## Description +
+Repetir una determinada cadena str (primer argumento) para num veces (segundo argumento). Devuelve una cadena vacía si num no es un número positivo. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' repeatStringNumTimes("*", 3) debe devolver "***" .' + testString: 'assert(repeatStringNumTimes("*", 3) === "***", "repeatStringNumTimes("*", 3) should return "***".");' + - text: ' repeatStringNumTimes("abc", 3) debe devolver "abcabcabc" .' + testString: 'assert(repeatStringNumTimes("abc", 3) === "abcabcabc", "repeatStringNumTimes("abc", 3) should return "abcabcabc".");' + - text: ' repeatStringNumTimes("abc", 4) debe devolver "abcabcabcabc" .' + testString: 'assert(repeatStringNumTimes("abc", 4) === "abcabcabcabc", "repeatStringNumTimes("abc", 4) should return "abcabcabcabc".");' + - text: ' repeatStringNumTimes("abc", 1) debe devolver "abc" .' + testString: 'assert(repeatStringNumTimes("abc", 1) === "abc", "repeatStringNumTimes("abc", 1) should return "abc".");' + - text: ' repeatStringNumTimes("*", 8) debe devolver "********" .' + testString: 'assert(repeatStringNumTimes("*", 8) === "********", "repeatStringNumTimes("*", 8) should return "********".");' + - text: ' repeatStringNumTimes("abc", -2) debe devolver "" .' + testString: 'assert(repeatStringNumTimes("abc", -2) === "", "repeatStringNumTimes("abc", -2) should return "".");' + - text: El método repeat() incorporado no debe utilizarse + testString: 'assert(!/\.repeat/g.test(code), "The built-in repeat()-method should not be used");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function repeatStringNumTimes(str, num) { + // repeat after me + return str; +} + +repeatStringNumTimes("abc", 3); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function repeatStringNumTimes(str, num) { + if (num < 0) return "; + return num === 1 ? str : str + repeatStringNumTimes(str, num-1); +} + +repeatStringNumTimes("abc", 3); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays.spanish.md new file mode 100644 index 0000000000..a8d9c08a7a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays.spanish.md @@ -0,0 +1,72 @@ +--- +id: a789b3483989747d63b0e427 +title: Return Largest Numbers in Arrays +localeTitle: Devolver los números más grandes en matrices +isRequired: true +challengeType: 5 +--- + +## Description +
+Devolver una matriz que consiste en el número más grande de cada sub-matriz proporcionada. Por simplicidad, la matriz provista contendrá exactamente 4 sub-matrices. +Recuerde, puede recorrer una matriz con un simple bucle for, y acceder a cada miembro con sintaxis de matriz arr[i] . +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) debe devolver una matriz. ' + testString: 'assert(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]).constructor === Array, "largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.");' + - text: ' largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) debe devolver [27, 5, 39, 1001] . + testString: 'assert.deepEqual(largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]), [27, 5, 39, 1001], "largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].");' + - text: ' largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) debe devolver [9, 35, 97, 1000000] . + testString: 'assert.deepEqual(largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]), [9, 35, 97, 1000000], "largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].");' + - text: ' largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) debe devolver [25, 48, 21, -3] . ' + testString: 'assert.deepEqual(largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]), [25, 48, 21, -3], "largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function largestOfFour(arr) { + // You can do this! + return arr; +} + +largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function largestOfFour(arr) { + return arr.map(subArr => Math.max.apply(null, subArr)); +} + +largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string.spanish.md new file mode 100644 index 0000000000..fe990a17be --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string.spanish.md @@ -0,0 +1,72 @@ +--- +id: a202eed8fc186c8434cb6d61 +title: Reverse a String +localeTitle: Revertir una cadena +isRequired: true +challengeType: 5 +--- + +## Description +
+Invertir la cadena proporcionada. +Es posible que deba convertir la cadena en una matriz antes de poder revertirla. +Su resultado debe ser una cadena. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: reverseString("hello") debe devolver una cadena. + testString: 'assert(typeof reverseString("hello") === "string", "reverseString("hello") should return a string.");' + - text: reverseString("hello") debe convertirse en "olleh" . + testString: 'assert(reverseString("hello") === "olleh", "reverseString("hello") should become "olleh".");' + - text: reverseString("Howdy") debe convertirse en "ydwoH" . + testString: 'assert(reverseString("Howdy") === "ydwoH", "reverseString("Howdy") should become "ydwoH".");' + - text: reverseString("Greetings from Earth") debe devolver "htraE morf sgniteerG" . + testString: 'assert(reverseString("Greetings from Earth") === "htraE morf sgniteerG", "reverseString("Greetings from Earth") should return "htraE morf sgniteerG".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function reverseString(str) { + return str; +} + +reverseString("hello"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function reverseString(str) { + return str.split('').reverse().join(''); +} + +reverseString("hello"); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice.spanish.md new file mode 100644 index 0000000000..c8294976be --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice.spanish.md @@ -0,0 +1,92 @@ +--- +id: 579e2a2c335b9d72dd32e05c +title: Slice and Splice +localeTitle: Rebanada y empalme +isRequired: true +isBeta: true +challengeType: 5 +--- + +## Description +
+Te dan dos matrices y un índice. +Utilice la matriz métodos slice y splice para copiar cada elemento de la primera matriz en la segunda matriz, en orden. +Comenzar a insertar elementos en el índice n de la segunda matriz. +Devuelve la matriz resultante. Las matrices de entrada deben permanecer iguales después de que se ejecute la función. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' frankenSplice([1, 2, 3], [4, 5], 1) debe devolver [4, 1, 2, 3, 5] .' + testString: 'assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5], "frankenSplice([1, 2, 3], [4, 5], 1) should return [4, 1, 2, 3, 5].");' + - text: ' frankenSplice([1, 2], ["a", "b"], 1) debe devolver ["a", 1, 2, "b"] .' + testString: 'assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ["a", 1, 2, "b"], "frankenSplice([1, 2], ["a", "b"], 1) should return ["a", 1, 2, "b"].");' + - text: ' frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2) debe devolver ["head", "shoulders", "claw", "tentacle", "knees", "toes"] . ' + testString: 'assert.deepEqual(frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2), ["head", "shoulders", "claw", "tentacle", "knees", "toes"], "frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2) should return ["head", "shoulders", "claw", "tentacle", "knees", "toes"].");' + - text: Todos los elementos de la primera matriz se deben agregar a la segunda matriz en su orden original. + testString: 'assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4], "All elements from the first array should be added to the second array in their original order.");' + - text: La primera matriz debe permanecer igual después de que se ejecute la función. + testString: 'assert(testArr1[0] === 1 && testArr1[1] === 2, "The first array should remain the same after the function runs.");' + - text: La segunda matriz debe permanecer igual después de que se ejecute la función. + testString: 'assert(testArr2[0] === "a" && testArr2[1] === "b", "The second array should remain the same after the function runs.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function frankenSplice(arr1, arr2, n) { + // It's alive. It's alive! + return arr2; +} + +frankenSplice([1, 2, 3], [4, 5, 6], 1); +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function frankenSplice(arr1, arr2, n) { + // It's alive. It's alive! + let result = arr2.slice(); + for (let i = 0; i < arr1.length; i++) { + result.splice(n+i, 0, arr1[i]); + } + return result; +} + +frankenSplice([1, 2, 3], [4, 5], 1); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence.spanish.md new file mode 100644 index 0000000000..c884304c3a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence.spanish.md @@ -0,0 +1,71 @@ +--- +id: ab6137d4e35944e21037b769 +title: Title Case a Sentence +localeTitle: Título Caso una oración +isRequired: true +challengeType: 5 +--- + +## Description +
+Devuelva la cadena provista con la primera letra de cada palabra en mayúscula. Asegúrese de que el resto de la palabra esté en minúscula. +A los efectos de este ejercicio, también debe poner mayúsculas en las palabras de conexión como "el" y "de". +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' titleCase("I'm a little tea pot") debería devolver una cadena.' + testString: 'assert(typeof titleCase("I"m a little tea pot") === "string", "titleCase("I'm a little tea pot") should return a string.");' + - text: ' titleCase("I'm a little tea pot") debería devolver I'm A Little Tea Pot '. + testString: 'assert(titleCase("I"m a little tea pot") === "I"m A Little Tea Pot", "titleCase("I'm a little tea pot") should return I'm A Little Tea Pot.");' + - text: titleCase("sHoRt AnD sToUt") debe devolver Short And Stout . + testString: 'assert(titleCase("sHoRt AnD sToUt") === "Short And Stout", "titleCase("sHoRt AnD sToUt") should return Short And Stout.");' + - text: titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") debería regresar. Here Is My Handle Here Is My Spout . + testString: 'assert(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") === "Here Is My Handle Here Is My Spout", "titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") should return Here Is My Handle Here Is My Spout.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function titleCase(str) { + return str; +} + +titleCase("I'm a little tea pot"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function titleCase(str) { + return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()).join(' '); +} + +titleCase("I'm a little tea pot"); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string.spanish.md new file mode 100644 index 0000000000..26a0c309ce --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string.spanish.md @@ -0,0 +1,79 @@ +--- +id: ac6993d51946422351508a41 +title: Truncate a String +localeTitle: Truncar una cadena +isRequired: true +challengeType: 5 +--- + +## Description +
+Truncar una cadena (primer argumento) si es más larga que la longitud de cadena máxima dada (segundo argumento). Devuelve la cadena truncada con un ... final. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' truncateString("A-tisket a-tasket A green and yellow basket", 8) debe devolver "A-tisket ...".' + testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", 8) === "A-tisket...", "truncateString("A-tisket a-tasket A green and yellow basket", 8) should return "A-tisket...".");' + - text: ' truncateString("Peter Piper picked a peck of pickled peppers", 11) debería devolver "Peter Piper ...". + testString: 'assert(truncateString("Peter Piper picked a peck of pickled peppers", 11) === "Peter Piper...", "truncateString("Peter Piper picked a peck of pickled peppers", 11) should return "Peter Piper...".");' + - text: ' truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) debe devolver "A-tisket a-tasket Una canasta verde y amarilla".' + testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) === "A-tisket a-tasket A green and yellow basket", "truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) should return "A-tisket a-tasket A green and yellow basket".");' + - text: ' truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) debe devolver "A-tisket a-tasket Una canasta verde y amarilla" . + testString: 'assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) === "A-tisket a-tasket A green and yellow basket", "truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2) should return "A-tisket a-tasket A green and yellow basket".");' + - text: ' truncateString("A-", 1) debe devolver "A ...".' + testString: 'assert(truncateString("A-", 1) === "A...", "truncateString("A-", 1) should return "A...".");' + - text: ' truncateString("Absolutely Longer", 2) debe devolver "Ab ...".' + testString: 'assert(truncateString("Absolutely Longer", 2) === "Ab...", "truncateString("Absolutely Longer", 2) should return "Ab...".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function truncateString(str, num) { + // Clear out that junk in your trunk + return str; +} + +truncateString("A-tisket a-tasket A green and yellow basket", 8); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function truncateString(str, num) { + if (num >= str.length) { + return str; + } + + return str.slice(0, num) + '...'; +} + +truncateString("A-tisket a-tasket A green and yellow basket", 8); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong.spanish.md new file mode 100644 index 0000000000..69899c82b5 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong.spanish.md @@ -0,0 +1,105 @@ +--- +id: a24c1a4622e3c05097f71d67 +title: Where do I Belong +localeTitle: Dónde pertenezco +isRequired: true +challengeType: 5 +--- + +## Description +
+Devuelva el índice más bajo en el que se debe insertar un valor (segundo argumento) en una matriz (primer argumento) una vez que se haya ordenado. El valor devuelto debe ser un número. +Por ejemplo, getIndexToIns([1,2,3,4], 1.5) debe devolver 1 porque es mayor que 1 (índice 0), pero menor que 2 (índice 1). +Del mismo modo, getIndexToIns([20,3,5], 19) debe devolver 2 porque una vez que se ha ordenado la matriz se verá como [3,5,20] y 19 es menor que 20 (índice 2) y mayor que 5 (índice 1). +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' getIndexToIns([10, 20, 30, 40, 50], 35) debe devolver 3 ' + testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3, "getIndexToIns([10, 20, 30, 40, 50], 35) should return 3.");' + - text: ' getIndexToIns([10, 20, 30, 40, 50], 35) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 35)) === "number", "getIndexToIns([10, 20, 30, 40, 50], 35) should return a number.");' + - text: ' getIndexToIns([10, 20, 30, 40, 50], 30) debe devolver 2 ' + testString: 'assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2, "getIndexToIns([10, 20, 30, 40, 50], 30) should return 2.");' + - text: ' getIndexToIns([10, 20, 30, 40, 50], 30) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([10, 20, 30, 40, 50], 30)) === "number", "getIndexToIns([10, 20, 30, 40, 50], 30) should return a number.");' + - text: ' getIndexToIns([40, 60], 50) debe devolver 1 ' + testString: 'assert(getIndexToIns([40, 60], 50) === 1, "getIndexToIns([40, 60], 50) should return 1.");' + - text: ' getIndexToIns([40, 60], 50) debe devolver un número.' + testString: 'assert(typeof(getIndexToIns([40, 60], 50)) === "number", "getIndexToIns([40, 60], 50) should return a number.");' + - text: ' getIndexToIns([3, 10, 5], 3) debe devolver 0 ' + testString: 'assert(getIndexToIns([3, 10, 5], 3) === 0, "getIndexToIns([3, 10, 5], 3) should return 0.");' + - text: ' getIndexToIns([3, 10, 5], 3) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([3, 10, 5], 3)) === "number", "getIndexToIns([3, 10, 5], 3) should return a number.");' + - text: ' getIndexToIns([5, 3, 20, 3], 5) debe devolver 2 ' + testString: 'assert(getIndexToIns([5, 3, 20, 3], 5) === 2, "getIndexToIns([5, 3, 20, 3], 5) should return 2.");' + - text: ' getIndexToIns([5, 3, 20, 3], 5) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([5, 3, 20, 3], 5)) === "number", "getIndexToIns([5, 3, 20, 3], 5) should return a number.");' + - text: ' getIndexToIns([2, 20, 10], 19) debe devolver 2 ' + testString: 'assert(getIndexToIns([2, 20, 10], 19) === 2, "getIndexToIns([2, 20, 10], 19) should return 2.");' + - text: ' getIndexToIns([2, 20, 10], 19) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([2, 20, 10], 19)) === "number", "getIndexToIns([2, 20, 10], 19) should return a number.");' + - text: ' getIndexToIns([2, 5, 10], 15) debe devolver 3 ' + testString: 'assert(getIndexToIns([2, 5, 10], 15) === 3, "getIndexToIns([2, 5, 10], 15) should return 3.");' + - text: ' getIndexToIns([2, 5, 10], 15) debe devolver un número'. + testString: 'assert(typeof(getIndexToIns([2, 5, 10], 15)) === "number", "getIndexToIns([2, 5, 10], 15) should return a number.");' + - text: ' getIndexToIns([], 1) debe devolver 0 ' + testString: 'assert(getIndexToIns([], 1) === 0, "getIndexToIns([], 1) should return 0.");' + - text: ' getIndexToIns([], 1) debe devolver un número.' + testString: 'assert(typeof(getIndexToIns([], 1)) === "number", "getIndexToIns([], 1) should return a number.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function getIndexToIns(arr, num) { + // Find my place in this sorted array. + return num; +} + +getIndexToIns([40, 60], 50); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function getIndexToIns(arr, num) { + arr = arr.sort((a, b) => a - b); + + for (let i = 0; i < arr.length; i++) { + if (arr[i] >= num) { + return i; + } + } + + return arr.length; +} + +getIndexToIns([40, 60], 50); + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for...in-statement.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for...in-statement.spanish.md new file mode 100644 index 0000000000..871b6da7eb --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/-iterate-through-the-keys-of-an-object-with-a-for...in-statement.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d7b7d367417b2b2512b1d +title: ' Iterate Through the Keys of an Object with a for...in Statement' +localeTitle: 'Iterar a través de las claves de un objeto con una for ... in Statement' +challengeType: 1 +--- + +## Description +
+A veces es posible que deba recorrer todas las claves dentro de un objeto. Esto requiere una sintaxis específica en JavaScript llamada for ... in statement. Para el objeto de nuestros users , esto podría verse como: +
for (let user in users) {
  console.log(user);
};

// logs:
Alan
Jeff
Sarah
Ryan
+En esta declaración, definimos una variable de user y, como puede ver, esta variable se restableció durante cada iteración de cada una de las claves del objeto a medida que la declaración se desplazaba a través del objeto, lo que daba como resultado que el nombre de cada usuario se imprimiera en la consola. +NOTA:
Los objetos no mantienen un orden para las claves almacenadas como lo hacen las matrices; por lo tanto, una posición de las teclas en un objeto, o el orden relativo en el que aparece, es irrelevante cuando se hace referencia o se accede a esa tecla. +
+ +## Instructions +
+Hemos definido una función, countOnline ; use una instrucción for ... in dentro de esta función para recorrer los usuarios en el objeto de los users y devolver el número de usuarios cuya propiedad en online está establecida en true . +
+ +## Tests +
+ +```yml +tests: + - text: El objeto users contiene a los usuarios Jeff y Ryan con online conjunto en online a true y los usuarios Alan y Sarah con online conjunto en online a false + testString: 'assert(users.Alan.online === false && users.Jeff.online === true && users.Sarah.online === false && users.Ryan.online === true, "The users object contains users Jeff and Ryan with online set to true and users Alan and Sarah with online set to false");' + - text: La función countOnline devuelve el número de usuarios con la propiedad en online establecida en true + testString: 'assert((function() { users.Harry = {online: true}; users.Sam = {online: true}; users.Carl = {online: true}; return countOnline(users) })() === 5, "The function countOnline returns the number of users with the online property set to true");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let users = { + Alan: { + age: 27, + online: false + }, + Jeff: { + age: 32, + online: true + }, + Sarah: { + age: 48, + online: false + }, + Ryan: { + age: 19, + online: true + } +}; + +function countOnline(obj) { + // change code below this line + + // change code above this line +} + +console.log(countOnline(users)); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation.spanish.md new file mode 100644 index 0000000000..05ba8bc091 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-an-arrays-contents-using-bracket-notation.spanish.md @@ -0,0 +1,70 @@ +--- +id: 5a661e0f1068aca922b3ef17 +title: Access an Array's Contents Using Bracket Notation +localeTitle: Acceder a los contenidos de una matriz usando notación de corchete +challengeType: 1 +--- + +## Description +
+La característica fundamental de cualquier estructura de datos es, por supuesto, la capacidad no solo de almacenar datos, sino también de poder recuperar esos datos en el comando. Entonces, ahora que hemos aprendido cómo crear una matriz, comencemos a pensar cómo podemos acceder a la información de esa matriz. +Cuando definimos una matriz simple como se ve a continuación, hay 3 elementos en ella: +
let ourArray = ["a", "b", "c"];
+En una matriz, cada elemento de la matriz tiene un índice . Este índice se duplica como la posición de ese elemento en la matriz y cómo se hace referencia a él. Sin embargo, es importante tener en cuenta que las matrices de JavaScript tienen un índice de cero , lo que significa que el primer elemento de una matriz está en realidad en la posición cero , no en el primero. +Para recuperar un elemento de una matriz, podemos encerrar un índice entre paréntesis y agregarlo al final de una matriz, o más comúnmente, a una variable que hace referencia a un objeto de matriz. Esto se conoce como notación de corchete . +Por ejemplo, si queremos recuperar la "a" de ourArray y asignarla a una variable, podemos hacerlo con el siguiente código: +
let ourVariable = ourArray[0];
// ourVariable equals "a"
+Además de acceder al valor asociado a un índice, también puede establecer un índice en un valor usando la misma notación: +
ourArray[1] = "not b anymore";
// ourArray now equals ["a", "not b anymore", "c"];
+Usando la notación de corchetes, ahora hemos restablecido el elemento en el índice 1 de "b" , a "not b anymore" . +
+ +## Instructions +
+Para completar este desafío, establezca la segunda posición (índice 1 ) de myArray en cualquier cosa que desee, además de "b" . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray[0] es igual a "a" ' + testString: 'assert.strictEqual(myArray[0], "a", "myArray[0] is equal to "a"");' + - text: ' myArray[1] ya no está configurado en "b" ' + testString: 'assert.notStrictEqual(myArray[1], "b", "myArray[1] is no longer set to "b"");' + - text: ' myArray[2] es igual a "c" ' + testString: 'assert.strictEqual(myArray[2], "c", "myArray[2] is equal to "c"");' + - text: ' myArray[3] es igual a "d" ' + testString: 'assert.strictEqual(myArray[3], "d", "myArray[3] is equal to "d"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let myArray = ["a", "b", "c", "d"]; +// change code below this line + +//change code above this line +console.log(myArray); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation.spanish.md new file mode 100644 index 0000000000..dd97e921f3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation.spanish.md @@ -0,0 +1,77 @@ +--- +id: 587d7b7c367417b2b2512b1a +title: Access Property Names with Bracket Notation +localeTitle: Acceso a nombres de propiedades con notación de corchete +challengeType: 1 +--- + +## Description +
+En el primer desafío de objetos mencionamos el uso de la notación de corchetes como una forma de acceder a los valores de las propiedades mediante la evaluación de una variable. Por ejemplo, imagine que nuestro objeto de foods se está utilizando en un programa para una caja registradora de un supermercado. Tenemos alguna función que configura los foods selectedFood y queremos verificar el objeto de nuestros foods para detectar la presencia de ese alimento. Esto podría parecer: +
let selectedFood = getCurrentFood(scannedItem);
let inventory = foods[selectedFood];
+Este código evaluará el valor almacenado en la variable selectedFood y devolverá el valor de esa clave en el objeto de foods , o undefined si no está presente. La notación de corchetes es muy útil porque a veces las propiedades de los objetos no se conocen antes del tiempo de ejecución o necesitamos acceder a ellos de una manera más dinámica. +
+ +## Instructions +
+Hemos definido una función, checkInventory , que recibe un elemento escaneado como un argumento. Devuelve el valor actual de la clave scannedItem en el objeto de foods . Puede suponer que solo se proporcionarán claves válidas como argumento para checkInventory . +
+ +## Tests +
+ +```yml +tests: + - text: checkInventory es una función + testString: 'assert.strictEqual(typeof checkInventory, "function", "checkInventory is a function");' + - text: 'El objeto de foods debe tener solo los siguientes pares clave-valor: apples: 25 , oranges: 32 , plums: 28 , bananas: 13 , grapes: 35 , strawberries: 27 ' + testString: 'assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, "The foods object should have only the following key-value pairs: apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27");' + - text: checkInventory("apples") debe devolver 25 + testString: 'assert.strictEqual(checkInventory("apples"), 25, "checkInventory("apples") should return 25");' + - text: checkInventory("bananas") debe devolver 13 + testString: 'assert.strictEqual(checkInventory("bananas"), 13, "checkInventory("bananas") should return 13");' + - text: checkInventory("strawberries") debe devolver 27 + testString: 'assert.strictEqual(checkInventory("strawberries"), 27, "checkInventory("strawberries") should return 27");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let foods = { + apples: 25, + oranges: 32, + plums: 28, + bananas: 13, + grapes: 35, + strawberries: 27 +}; +// do not change code above this line + +function checkInventory(scannedItem) { + // change code below this line + +} + +// change code below this line to test different cases: +console.log(checkInventory("apples")); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift.spanish.md new file mode 100644 index 0000000000..96e9f5f9e9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d78b2367417b2b2512b0e +title: Add Items to an Array with push() and unshift() +localeTitle: Agregar elementos a una matriz con push () y unshift () +challengeType: 1 +--- + +## Description +
+La longitud de una matriz, como los tipos de datos que puede contener, no es fija. Las matrices se pueden definir con una longitud de cualquier número de elementos, y los elementos se pueden agregar o eliminar con el tiempo; en otras palabras, los arreglos son mutables . En este desafío, veremos dos métodos con los cuales podemos modificar mediante programación una matriz: Array.push() y Array.unshift() . +Ambos métodos toman uno o más elementos como parámetros y agregan esos elementos a la matriz en la que se está utilizando el método; el método push() agrega elementos al final de una matriz, y unshift() agrega elementos al principio. Considera lo siguiente: +
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];

romanNumerals.unshift('XIX', 'XX');
// now equals ['XIX', 'XX', 'XXI', 'XXII']

romanNumerals.push(twentyThree);
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII'] +Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data. +
+ +## Instructions +
+Hemos definido una función, mixedNumbers , a la que le estamos pasando una matriz como argumento. Modifique la función utilizando push() y unshift() para agregar 'I', 2, 'three' al principio de la matriz y 7, 'VIII', 9 al final para que la matriz devuelta contenga representaciones de los números 1-9 en orden. +
+ +## Tests +
+ +```yml +tests: + - text: ' mixedNumbers(["IV", 5, "six"]) ahora debe devolver ["I", 2, "three", "IV", 5, "six", 7, "VIII", 9] ' + testString: 'assert.deepEqual(mixedNumbers(["IV", 5, "six"]), ["I", 2, "three", "IV", 5, "six", 7, "VIII", 9], "mixedNumbers(["IV", 5, "six"]) should now return ["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]");' + - text: La función mixedNumbers debe utilizar el método push() + testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.push\(/), -1, "The mixedNumbers function should utilize the push() method");' + - text: La función mixedNumbers debe utilizar el método unshift() + testString: 'assert.notStrictEqual(mixedNumbers.toString().search(/\.unshift\(/), -1, "The mixedNumbers function should utilize the unshift() method");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function mixedNumbers(arr) { + // change code below this line + + // change code above this line + return arr; +} + +// do not change code below this line +console.log(mixedNumbers(['IV', 5, 'six'])); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.spanish.md new file mode 100644 index 0000000000..ab2e3d2fcc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-items-using-splice.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d78b3367417b2b2512b11 +title: Add Items Using splice() +localeTitle: Agregar artículos usando splice () +challengeType: 1 +--- + +## Description +
+Recuerda que en el último desafío mencionamos que splice() puede tomar hasta tres parámetros? Bueno, podemos ir un paso más allá con splice() ; además de eliminar elementos, podemos usar ese tercer parámetro, que representa uno o más elementos, para agregarlos también. Esto puede ser increíblemente útil para cambiar rápidamente un elemento, o un conjunto de elementos, por otro. Por ejemplo, supongamos que está almacenando una combinación de colores para un conjunto de elementos DOM en una matriz, y desea cambiar dinámicamente un color en función de alguna acción: +
function colorChange(arr, index, newColor) {
  arr.splice(index, 1, newColor);
  return arr;
}

let colorScheme = ['#878787', '#a08794', '#bb7e8c', '#c9b6be', '#d1becf'];

colorScheme = colorChange(colorScheme, 2, '#332327');
// we have removed '#bb7e8c' and added '#332327' in its place
// colorScheme now equals ['#878787', '#a08794', '#332327', '#c9b6be', '#d1becf']
+Esta función toma una matriz de valores hexadecimales, un índice para eliminar un elemento y el nuevo color para reemplazar el elemento eliminado. El valor de retorno es una matriz que contiene un esquema de color recién modificado. Si bien este ejemplo está un poco simplificado, podemos ver el valor que puede tener el uso de splice() en su potencial máximo. +
+ +## Instructions +
+Hemos definido una función, htmlColorNames , que toma una matriz de colores HTML como argumento. Modifique la función utilizando splice() para eliminar los dos primeros elementos de la matriz y agregue 'DarkSalmon' y 'BlanchedAlmond' en sus respectivos lugares. +
+ +## Tests +
+ +```yml +tests: + - text: ' htmlColorNames debería devolver ["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"] ' + testString: 'assert.deepEqual(htmlColorNames(["DarkGoldenRod", "WhiteSmoke", "LavenderBlush", "PaleTurqoise", "FireBrick"]), ["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"], "htmlColorNames should return ["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurqoise", "FireBrick"]");' + - text: La función htmlColorNames debe utilizar el método splice() + testString: 'assert(/.splice/.test(code), "The htmlColorNames function should utilize the splice() method");' + - text: No debes usar shift() o unshift() . + testString: 'assert(!/shift|unshift/.test(code), "You should not use shift() or unshift().");' + - text: No debe utilizar la notación de soporte de matriz. + testString: 'assert(!/\[\d\]\s*=/.test(code), "You should not use array bracket notation.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function htmlColorNames(arr) { + // change code below this line + + // change code above this line + return arr; +} + +// do not change code below this line +console.log(htmlColorNames(['DarkGoldenRod', 'WhiteSmoke', 'LavenderBlush', 'PaleTurqoise', 'FireBrick'])); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.spanish.md new file mode 100644 index 0000000000..dd908a806d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7b7c367417b2b2512b18 +title: Add Key-Value Pairs to JavaScript Objects +localeTitle: Agregue pares de valor-clave a los objetos de JavaScript +challengeType: 1 +--- + +## Description +
+En su forma más básica, los objetos son solo colecciones de pares clave-valor , o, en otras palabras, fragmentos de datos asignados a identificadores únicos que llamamos propiedades o claves . Veamos un ejemplo muy simple: +
let FCC_User = {
  username: 'awesome_coder',
  followers: 572,
  points: 1741,
  completedProjects: 15
};
+El código anterior define un objeto llamado FCC_User que tiene cuatro propiedades , cada una de las cuales se FCC_User a un valor específico. Si quisiéramos saber el número de followers tiene FCC_User , podemos acceder a esa propiedad escribiendo: +
let userData = FCC_User.followers;
// userData equals 572
+Esto se llama notación de puntos . Alternativamente, también podemos acceder a la propiedad entre paréntesis, así: +
let userData = FCC_User['followers']
// userData equals 572
+Observe que con la notación de corchetes , incluimos a los followers entre comillas. Esto se debe a que los corchetes realmente nos permiten pasar una variable para que sea evaluada como un nombre de propiedad (sugerencia: ten esto en cuenta para más adelante). Si hubiéramos pasado a los followers sin las comillas, el motor de JavaScript habría intentado evaluarla como una variable, y un ReferenceError: followers is not defined . +
+ +## Instructions +
+Usando la misma sintaxis, también podemos agregar nuevos pares clave-valor a los objetos. Hemos creado un objeto de foods con tres entradas. Agregue tres entradas más: bananas con un valor de 13 , grapes con un valor de 35 y strawberries con un valor de 27 . +
+ +## Tests +
+ +```yml +tests: + - text: foods son un objeto + testString: 'assert(typeof foods === "object", "foods is an object");' + - text: El objeto foods tiene una clave "bananas" con un valor de 13 + testString: 'assert(foods.bananas === 13, "The foods object has a key "bananas" with a value of 13");' + - text: El objeto foods tiene una clave "grapes" con un valor de 35 + testString: 'assert(foods.grapes === 35, "The foods object has a key "grapes" with a value of 35");' + - text: El objeto de foods tiene una clave "strawberries" con un valor de 27 + testString: 'assert(foods.strawberries === 27, "The foods object has a key "strawberries" with a value of 27");' + - text: Los pares clave-valor deben configurarse usando notación de punto o corchete + testString: 'assert(code.search(/bananas:/) === -1 && code.search(/grapes:/) === -1 && code.search(/strawberries:/) === -1, "The key-value pairs should be set using dot or bracket notation");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let foods = { + apples: 25, + oranges: 32, + plums: 28 +}; + +// change code below this line + +// change code above this line + +console.log(foods); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.spanish.md new file mode 100644 index 0000000000..372c20f705 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7b7b367417b2b2512b14 +title: Check For The Presence of an Element With indexOf() +localeTitle: Comprobar la presencia de un elemento con indexOf () +challengeType: 1 +--- + +## Description +
+Dado que las matrices se pueden cambiar, o mutar , en cualquier momento, no hay ninguna garantía sobre dónde estará una determinada pieza de datos en una matriz determinada, o si ese elemento aún existe. Afortunadamente, JavaScript nos proporciona otro método indexOf() , indexOf() , que nos permite verificar rápida y fácilmente la presencia de un elemento en una matriz. indexOf() toma un elemento como parámetro y, cuando se le llama, devuelve la posición o el índice de ese elemento, o -1 si el elemento no existe en la matriz. +Por ejemplo: +
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];

fruits.indexOf('dates') // returns -1
fruits.indexOf('oranges') // returns 2
fruits.indexOf('pears') // returns 1, the first index at which the element exists
+
+ +## Instructions +
+indexOf() puede ser increíblemente útil para verificar rápidamente la presencia de un elemento en una matriz. Hemos definido una función, quickCheck , que toma una matriz y un elemento como argumentos. Modifique la función utilizando indexOf() para que devuelva true si el elemento pasado existe en la matriz, y false si no lo hace. +
+ +## Tests +
+ +```yml +tests: + - text: ' quickCheck(["squash", "onions", "shallots"], "mushrooms") debe devolver false ' + testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "mushrooms"), false, "quickCheck(["squash", "onions", "shallots"], "mushrooms") should return false");' + - text: ' quickCheck(["squash", "onions", "shallots"], "onions") debe devolver true " + testString: 'assert.strictEqual(quickCheck(["squash", "onions", "shallots"], "onions"), true, "quickCheck(["squash", "onions", "shallots"], "onions") should return true");' + - text: ' quickCheck([3, 5, 9, 125, 45, 2], 125) debe devolver true ' + testString: 'assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true, "quickCheck([3, 5, 9, 125, 45, 2], 125) should return true");' + - text: ' quickCheck([true, false, false], undefined) debe devolver false ' + testString: 'assert.strictEqual(quickCheck([true, false, false], undefined), false, "quickCheck([true, false, false], undefined) should return false");' + - text: La función quickCheck debe utilizar el método indexOf() + testString: 'assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1, "The quickCheck function should utilize the indexOf() method");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function quickCheck(arr, elem) { + // change code below this line + + // change code above this line +} + +// change code here to test different cases: +console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms')); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.spanish.md new file mode 100644 index 0000000000..405f991260 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/check-if-an-object-has-a-property.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d7b7d367417b2b2512b1c +title: Check if an Object has a Property +localeTitle: Compruebe si un objeto tiene una propiedad +challengeType: 1 +--- + +## Description +
+Ahora podemos agregar, modificar y eliminar claves de objetos. Pero, ¿y si solo quisiéramos saber si un objeto tiene una propiedad específica? JavaScript nos proporciona dos formas diferentes de hacer esto. Uno usa el método hasOwnProperty() y el otro usa la palabra clave in . Si tenemos un objeto users con una propiedad de Alan , podríamos verificar su presencia de una de las siguientes maneras: +
users.hasOwnProperty('Alan');
'Alan' in users;
// both return true
+
+ +## Instructions +
+Hemos creado un objeto, users , con algunos usuarios en él y una función isEveryoneHere , a la que pasamos el objeto de los users como un argumento. Termine de escribir esta función de modo que devuelva true solo si el objeto de los users contiene los cuatro nombres, Alan , Jeff , Sarah y Ryan , como claves, y en caso contrario, false . +
+ +## Tests +
+ +```yml +tests: + - text: 'El objeto de los users solo contiene las claves Alan , Jeff , Sarah y Ryan ' + testString: 'assert("Alan" in users && "Jeff" in users && "Sarah" in users && "Ryan" in users && Object.keys(users).length === 4, "The users object only contains the keys Alan, Jeff, Sarah, and Ryan");' + - text: 'La función isEveryoneHere devuelve true si Alan , Jeff , Sarah y Ryan son propiedades del objeto de los users ' + testString: 'assert(isEveryoneHere(users) === true, "The function isEveryoneHere returns true if Alan, Jeff, Sarah, and Ryan are properties on the users object");' + - text: 'La función isEveryoneHere devuelve false si Alan , Jeff , Sarah y Ryan no son propiedades del objeto de los users ' + testString: 'assert((function() { delete users.Alan; delete users.Jeff; delete users.Sarah; delete users.Ryan; return isEveryoneHere(users) })() === false, "The function isEveryoneHere returns false if Alan, Jeff, Sarah, and Ryan are not properties on the users object");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let users = { + Alan: { + age: 27, + online: true + }, + Jeff: { + age: 32, + online: true + }, + Sarah: { + age: 48, + online: true + }, + Ryan: { + age: 19, + online: true + } +}; + +function isEveryoneHere(obj) { + // change code below this line + + // change code above this line +} + +console.log(isEveryoneHere(users)); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.spanish.md new file mode 100644 index 0000000000..7da17657cc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/combine-arrays-with-the-spread-operator.spanish.md @@ -0,0 +1,62 @@ +--- +id: 587d7b7b367417b2b2512b17 +title: Combine Arrays with the Spread Operator +localeTitle: Combina matrices con el operador de propagación +challengeType: 1 +--- + +## Description +
+Otra gran ventaja del operador de difusión , es la capacidad de combinar arreglos, o de insertar todos los elementos de un arreglo en otro, en cualquier índice. Con sintaxis más tradicionales, podemos concatenar matrices, pero esto solo nos permite combinar matrices al final de una y al comienzo de otra. La sintaxis de propagación hace que la siguiente operación sea extremadamente simple: +
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];

let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
// thatArray now equals ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']
+Usando la sintaxis de propagación, acabamos de lograr una operación que hubiera sido más compleja y más detallada si hubiéramos usado métodos tradicionales. +
+ +## Instructions +
+Hemos definido una función spreadOut que devuelve la sentence variable, modifique la función usando el operador de propagación para que devuelva la matriz ['learning', 'to', 'code', 'is', 'fun'] . +
+ +## Tests +
+ +```yml +tests: + - text: ' spreadOut debería devolver ["learning", "to", "code", "is", "fun"] ' + testString: 'assert.deepEqual(spreadOut(), ["learning", "to", "code", "is", "fun"], "spreadOut should return ["learning", "to", "code", "is", "fun"]");' + - text: La función spreadOut debe utilizar la sintaxis de difusión + testString: 'assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1, "The spreadOut function should utilize spread syntax");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function spreadOut() { + let fragment = ['to', 'code']; + let sentence; // change this line + return sentence; +} + +// do not change code below this line +console.log(spreadOut()); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.spanish.md new file mode 100644 index 0000000000..e4c92a3ade --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-an-array-with-the-spread-operator.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7b7b367417b2b2512b13 +title: Copy an Array with the Spread Operator +localeTitle: Copiar una matriz con el operador de propagación +challengeType: 1 +--- + +## Description +
+Mientras slice() nos permite ser selectivos sobre qué elementos de una matriz copiar, entre otras muchas tareas útiles, el nuevo operador de difusión de ES6 nos permite copiar fácilmente todos los elementos de una matriz, en orden, con una sintaxis simple y altamente legible . La sintaxis de propagación simplemente se ve así: ... +En la práctica, podemos usar el operador de propagación para copiar una matriz de la siguiente manera: +
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
// thatArray equals [true, true, undefined, false, null]
// thisArray remains unchanged, and is identical to thatArray
+
+ +## Instructions +
+Hemos definido una función, copyMachine que toma arr (una matriz) y num (un número) como argumentos. Se supone que la función devuelve una nueva matriz formada por num copias de arr . Hemos hecho la mayor parte del trabajo por usted, pero todavía no funciona del todo bien. Modifique la función utilizando la sintaxis de dispersión para que funcione correctamente (sugerencia: ¡otro método que ya hemos cubierto podría ser útil aquí!). +
+ +## Tests +
+ +```yml +tests: + - text: ' copyMachine([true, false, true], 2) debe devolver [[true, false, true], [true, false, true]] ' + testString: 'assert.deepEqual(copyMachine([true, false, true], 2), [[true, false, true], [true, false, true]], "copyMachine([true, false, true], 2) should return [[true, false, true], [true, false, true]]");' + - text: ' copyMachine([1, 2, 3], 5) debe devolver [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] ' + testString: 'assert.deepEqual(copyMachine([1, 2, 3], 5), [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]], "copyMachine([1, 2, 3], 5) should return [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]");' + - text: ' copyMachine([true, true, null], 1) debe devolver [[true, true, null]] ' + testString: 'assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]], "copyMachine([true, true, null], 1) should return [[true, true, null]]");' + - text: ' copyMachine(["it works"], 3) debería devolver [["it works"], ["it works"], ["it works"]] ' + testString: 'assert.deepEqual(copyMachine(["it works"], 3), [["it works"], ["it works"], ["it works"]], "copyMachine(["it works"], 3) should return [["it works"], ["it works"], ["it works"]]");' + - text: La función copyMachine debe utilizar el spread operator con array arr + testString: 'assert.notStrictEqual(copyMachine.toString().indexOf(".concat(_toConsumableArray(arr))"), -1, "The copyMachine function should utilize the spread operator with array arr");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function copyMachine(arr, num) { + let newArr = []; + while (num >= 1) { + // change code below this line + + // change code above this line + num--; + } + return newArr; +} + +// change code here to test different cases: +console.log(copyMachine([true, false, true], 2)); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.spanish.md new file mode 100644 index 0000000000..71ba55b3e4 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/copy-array-items-using-slice.spanish.md @@ -0,0 +1,62 @@ +--- +id: 587d7b7a367417b2b2512b12 +title: Copy Array Items Using slice() +localeTitle: Copiar elementos de matriz utilizando slice () +challengeType: 1 +--- + +## Description +
+El siguiente método que cubriremos es slice() . slice() , en lugar de modificar una matriz, copia o extrae , un número dado de elementos a una nueva matriz, dejando la matriz a la que se llama sin tocar. slice() toma solo 2 parámetros: el primero es el índice para comenzar la extracción y el segundo es el índice para detener la extracción (la extracción ocurrirá hasta, pero sin incluir el elemento en este índice). Considera esto: +
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];

let todaysWeather = weatherConditions.slice(1, 3);
// todaysWeather equals ['snow', 'sleet'];
// weatherConditions still equals ['rain', 'snow', 'sleet', 'hail', 'clear']
+En efecto, hemos creado una nueva matriz extrayendo elementos de una matriz existente. +
+ +## Instructions +
+Hemos definido una función, forecast , que toma una matriz como argumento. Modifique la función utilizando slice() para extraer información de la matriz de argumentos y devuelva una nueva matriz que contenga los elementos 'warm' y 'sunny' . +
+ +## Tests +
+ +```yml +tests: + - text: ' forecast debería devolver ["warm", "sunny"]' + testString: 'assert.deepEqual(forecast(["cold", "rainy", "warm", "sunny", "cool", "thunderstorms"]), ["warm", "sunny"], "forecast should return ["warm", "sunny"]");' + - text: La función de forecast debe utilizar el método slice() + testString: 'assert(/\.slice\(/.test(code), "The forecast function should utilize the slice() method");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function forecast(arr) { + // change code below this line + + return arr; +} + +// do not change code below this line +console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms'])); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.spanish.md new file mode 100644 index 0000000000..a4d226cfdd --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/create-complex-multi-dimensional-arrays.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d7b7b367417b2b2512b16 +title: Create complex multi-dimensional arrays +localeTitle: Crear complejos arreglos multidimensionales. +challengeType: 1 +--- + +## Description +
+impresionante! ¡Acabas de aprender un montón de arreglos! Este ha sido un resumen de nivel bastante alto, y hay mucho más que aprender sobre el trabajo con matrices, muchas de las cuales veremos en secciones posteriores. Pero antes de pasar a mirar Objetos , echemos un vistazo más y veamos cómo los arreglos pueden volverse un poco más complejos de lo que hemos visto en desafíos anteriores. +Una de las características más poderosas cuando se piensa en los arreglos como estructuras de datos, es que los arreglos pueden contener, o incluso estar completamente compuestos de otros arreglos. Hemos visto matrices que contienen matrices en desafíos anteriores, pero bastante simples. Sin embargo, las matrices pueden contener una profundidad infinita de matrices que pueden contener otras matrices, cada una con sus propios niveles arbitrarios de profundidad, y así sucesivamente. De esta manera, una matriz puede convertirse muy rápidamente en una estructura de datos muy compleja, conocida como una matriz multidimensional o anidada. Considera el siguiente ejemplo: +
let nestedArray = [ // top, or first level - the outer most array
  ['deep'], // an array within an array, 2 levels of depth
  [
    ['deeper'], ['deeper'] // 2 arrays nested 3 levels deep
  ],
  [
    [
      ['deepest'], ['deepest'] // 2 arrays nested 4 levels deep
    ],
    [
      [
        ['deepest-est?'] // an array nested 5 levels deep
      ]
    ]
  ]
];
+Si bien este ejemplo puede parecer complicado, este nivel de complejidad no es inaudito, o incluso inusual, cuando se trata de grandes cantidades de datos. +Sin embargo, aún podemos acceder fácilmente a los niveles más profundos de una matriz de este complejo con notación de corchete: +
console.log(nestedArray[2][1][0][0][0]);
// logs: deepest-est?
+Y ahora que sabemos dónde está ese dato, podemos restablecerlo si necesitamos: +
nestedArray[2][1][0][0][0] = 'deeper still';

console.log(nestedArray[2][1][0][0][0]);
// now logs: deeper still
+
+ +## Instructions +
+Hemos definido una variable, myNestedArray , igual a una matriz. Modifique myNestedArray , utilizando cualquier combinación de cadenas , números y valores booleanos para los elementos de datos, de modo que tenga exactamente cinco niveles de profundidad (recuerde, la matriz más externa es el nivel 1). En algún lugar en el tercer nivel, incluye la cadena 'deep' , en el cuarto nivel, incluyen la cadena 'deeper' , y en el quinto nivel, incluyen la cadena 'deepest' . +
+ +## Tests +
+ +```yml +tests: + - text: ' myNestedArray debe contener solo números, booleanos y cadenas como elementos de datos' + testString: 'assert.strictEqual((function(arr) { let flattened = (function flatten(arr) { const flat = [].concat(...arr); return flat.some (Array.isArray) ? flatten(flat) : flat; })(arr); for (let i = 0; i < flattened.length; i++) { if ( typeof flattened[i] !== "number" && typeof flattened[i] !== "string" && typeof flattened[i] !== "boolean") { return false } } return true })(myNestedArray), true, "myNestedArray should contain only numbers, booleans, and strings as data elements");' + - text: myNestedArray debe tener exactamente 5 niveles de profundidad + testString: 'assert.strictEqual((function(arr) {let depth = 0;function arrayDepth(array, i, d) { if (Array.isArray(array[i])) { arrayDepth(array[i], 0, d + 1);} else { depth = (d > depth) ? d : depth;}if (i < array.length) { arrayDepth(array, i + 1, d);} }arrayDepth(arr, 0, 0);return depth;})(myNestedArray), 4, "myNestedArray should have exactly 5 levels of depth");' + - text: myNestedArray debe contener exactamente una aparición de la cadena "deep" en una matriz anidada con 3 niveles de profundidad + testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deep").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deep")[0] === 2, "myNestedArray should contain exactly one occurrence of the string "deep" on an array nested 3 levels deep");' + - text: myNestedArray debe contener exactamente una aparición de la cadena "deeper" deep "deeper" en una matriz anidada con 4 niveles de profundidad + testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deeper").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deeper")[0] === 3, "myNestedArray should contain exactly one occurrence of the string "deeper" on an array nested 4 levels deep");' + - text: myNestedArray debe contener exactamente una aparición de la cadena "deepest" en una matriz anidada a 5 niveles de profundidad + testString: 'assert((function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deepest").length === 1 && (function howDeep(array, target, depth = 0) {return array.reduce((combined, current) => {if (Array.isArray(current)) { return combined.concat(howDeep(current, target, depth + 1));} else if (current === target) { return combined.concat(depth);} else { return combined;}}, []);})(myNestedArray, "deepest")[0] === 4, "myNestedArray should contain exactly one occurrence of the string "deepest" on an array nested 5 levels deep");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let myNestedArray = [ + // change code below this line + ['unshift', false, 1, 2, 3, 'complex', 'nested'], + ['loop', 'shift', 6, 7, 1000, 'method'], + ['concat', false, true, 'spread', 'array'], + ['mutate', 1327.98, 'splice', 'slice', 'push'], + ['iterate', 1.3849, 7, '8.4876', 'arbitrary', 'depth'] + // change code above this line +]; +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object.keys.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object.keys.spanish.md new file mode 100644 index 0000000000..00b7829c94 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/generate-an-array-of-all-object-keys-with-object.keys.spanish.md @@ -0,0 +1,78 @@ +--- +id: 587d7b7d367417b2b2512b1e +title: Generate an Array of All Object Keys with Object.keys() +localeTitle: Generar una matriz de todas las claves de objeto con Object.keys () +challengeType: 1 +--- + +## Description +
+También podemos generar una matriz que contiene todas las claves almacenadas en un objeto usando el método Object.keys() y pasando un objeto como argumento. Esto devolverá una matriz con cadenas que representan cada propiedad en el objeto. Nuevamente, no habrá un orden específico para las entradas en la matriz. +
+ +## Instructions +
+Termine de escribir la función getArrayOfUsers para que devuelva una matriz que contenga todas las propiedades en el objeto que recibe como argumento. +
+ +## Tests +
+ +```yml +tests: + - text: 'El objeto de los users solo contiene las claves Alan , Jeff , Sarah y Ryan ' + testString: 'assert("Alan" in users && "Jeff" in users && "Sarah" in users && "Ryan" in users && Object.keys(users).length === 4, "The users object only contains the keys Alan, Jeff, Sarah, and Ryan");' + - text: La función getArrayOfUsers devuelve una matriz que contiene todas las claves en el objeto de los users + testString: 'assert((function() { users.Sam = {}; users.Lewis = {}; let R = getArrayOfUsers(users); return (R.indexOf("Alan") !== -1 && R.indexOf("Jeff") !== -1 && R.indexOf("Sarah") !== -1 && R.indexOf("Ryan") !== -1 && R.indexOf("Sam") !== -1 && R.indexOf("Lewis") !== -1); })() === true, "The getArrayOfUsers function returns an array which contains all the keys in the users object");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let users = { + Alan: { + age: 27, + online: false + }, + Jeff: { + age: 32, + online: true + }, + Sarah: { + age: 48, + online: false + }, + Ryan: { + age: 19, + online: true + } +}; + +function getArrayOfUsers(obj) { + // change code below this line + + // change code above this line +} + +console.log(getArrayOfUsers(users)); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.spanish.md new file mode 100644 index 0000000000..11356a8372 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops.spanish.md @@ -0,0 +1,71 @@ +--- +id: 587d7b7b367417b2b2512b15 +title: Iterate Through All an Array's Items Using For Loops +localeTitle: Iterar a través de todos los elementos de una matriz utilizando bucles for +challengeType: 1 +--- + +## Description +
+A veces, cuando se trabaja con matrices, es muy útil poder recorrer cada elemento para encontrar uno o más elementos que podríamos necesitar, o manipular una matriz en función de qué elementos de datos cumplen un determinado conjunto de criterios. JavaScript ofrece varios métodos integrados que se repiten en matrices de maneras ligeramente diferentes para lograr resultados diferentes (como every() , para forEach() , map() , etc.), sin embargo, la técnica es más flexible y nos ofrece la mejor cantidad de control es un simple for bucle. +Considera lo siguiente: +
function greaterThanTen(arr) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 10) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
// returns [12, 14, 80]
+Usando un bucle for , esta función recorre y accede a cada elemento de la matriz, y lo somete a una prueba simple que hemos creado. De esta manera, hemos determinado fácil y programáticamente qué elementos de datos son más grandes que 10 , y hemos devuelto una nueva matriz que contiene esos elementos. +
+ +## Instructions +
+Hemos definido una función, filteredArray , que toma arr , una matriz anidada, y elem como argumentos, y devuelve una nueva matriz. elem representa un elemento que puede o no estar presente en una o más de las matrices anidadas dentro de arr . Modifique la función, utilizando un bucle for , para devolver una versión filtrada de la matriz pasada de manera que se haya eliminado cualquier matriz anidada dentro de arr contenga elem . +
+ +## Tests +
+ +```yml +tests: + - text: ' filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) debe devolver [ [10, 8, 3], [14, 6, 23] ] ' + testString: 'assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]], "filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18) should return [ [10, 8, 3], [14, 6, 23] ]");' + - text: ' filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2) debe devolver [ ["flutes", 4] ] ' + testString: 'assert.deepEqual(filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2), [["flutes", 4]], "filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2) should return [ ["flutes", 4] ]");' + - text: ' filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter") debe devolver [ ["amy", "beth", "sam"] ] ' + testString: 'assert.deepEqual(filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter"), [["amy", "beth", "sam"]], "filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter") should return [ ["amy", "beth", "sam"] ]");' + - text: ' filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3) debe devolver [ ] ' + testString: 'assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), [], "filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3) should return [ ]");' + - text: El filteredArray función debe utilizar un for bucle + testString: 'assert.notStrictEqual(filteredArray.toString().search(/for/), -1, "The filteredArray function should utilize a for loop");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function filteredArray(arr, elem) { + let newArr = []; + // change code below this line + + // change code above this line + return newArr; +} + +// change code here to test different cases: +console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object.spanish.md new file mode 100644 index 0000000000..d851c1bdfe --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-array-stored-in-an-object.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d7b7d367417b2b2512b1f +title: Modify an Array Stored in an Object +localeTitle: Modificar una matriz almacenada en un objeto +challengeType: 1 +--- + +## Description +
+Ahora has visto todas las operaciones básicas para objetos JavaScript. Puede agregar, modificar y eliminar pares clave-valor, verificar si existen claves e iterar sobre todas las claves en un objeto. A medida que continúe aprendiendo JavaScript, verá aplicaciones de objetos aún más versátiles. Además, las lecciones opcionales de Estructuras de datos avanzadas más adelante en el plan de estudios también cubren los objetos Map y Set de ES6, los cuales son similares a los objetos comunes pero ofrecen algunas características adicionales. ¡Ahora que ha aprendido los conceptos básicos de matrices y objetos, está completamente preparado para comenzar a abordar problemas más complejos utilizando JavaScript! +
+ +## Instructions +
+Eche un vistazo al objeto que hemos proporcionado en el editor de código. El objeto de user contiene tres claves. La clave de data contiene cinco claves, una de las cuales contiene una gran variedad de friends . A partir de esto, puede ver cómo los objetos flexibles son como estructuras de datos. Hemos empezado a escribir una función addFriend . Termine de escribirlo para que tome un objeto de user y agregue el nombre del argumento de friend a la matriz almacenada en user.data.friends y devuelva esa matriz. +
+ +## Tests +
+ +```yml +tests: + - text: 'El objeto de user tiene name , age y claves de data ' + testString: 'assert("name" in user && "age" in user && "data" in user, "The user object has name, age, and data keys");' + - text: La función addFriend acepta un objeto de user y una cadena de friend como argumentos y agrega el amigo a la matriz de friends en el objeto de user + testString: 'assert((function() { let L1 = user.data.friends.length; addFriend(user, "Sean"); let L2 = user.data.friends.length; return (L2 === L1 + 1); })(), "The addFriend function accepts a user object and a friend string as arguments and adds the friend to the array of friends in the user object");' + - text: ' addFriend(user, "Pete") debe devolver ["Sam", "Kira", "Tomo", "Pete"] ' + testString: 'assert.deepEqual((function() { delete user.data.friends; user.data.friends = ["Sam", "Kira", "Tomo"]; return addFriend(user, "Pete") })(), ["Sam", "Kira", "Tomo", "Pete"], "addFriend(user, "Pete") should return ["Sam", "Kira", "Tomo", "Pete"]");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let user = { + name: 'Kenneth', + age: 28, + data: { + username: 'kennethCodesAllDay', + joinDate: 'March 26, 2016', + organization: 'freeCodeCamp', + friends: [ + 'Sam', + 'Kira', + 'Tomo' + ], + location: { + city: 'San Francisco', + state: 'CA', + country: 'USA' + } + } +}; + +function addFriend(userObj, friend) { + // change code below this line + + // change code above this line +} + +console.log(addFriend(user, 'Pete')); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object.spanish.md new file mode 100644 index 0000000000..61e7211b0e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/modify-an-object-nested-within-an-object.spanish.md @@ -0,0 +1,72 @@ +--- +id: 587d7b7c367417b2b2512b19 +title: Modify an Object Nested Within an Object +localeTitle: Modificar un objeto anidado dentro de un objeto +challengeType: 1 +--- + +## Description +
+Ahora veamos un objeto un poco más complejo. Las propiedades de los objetos se pueden anidar a una profundidad arbitraria, y sus valores pueden ser cualquier tipo de datos admitidos por JavaScript, incluidas las matrices e incluso otros objetos. Considera lo siguiente: +
let nestedObject = {
  id: 28802695164,
  date: 'December 31, 2016',
  data: {
    totalUsers: 99,
    online: 80,
    onlineStatus: {
      active: 67,
      away: 13
    }
  }
};
+nestedObject tiene tres claves únicas: id , cuyo valor es un número, la date cuyo valor es una cadena y los data , cuyo valor es un objeto que tiene otro objeto anidado dentro de él. Si bien las estructuras pueden volverse complejas rápidamente, aún podemos usar las mismas notaciones para acceder a la información que necesitamos. +
+ +## Instructions +
+Aquí hemos definido un objeto, userActivity , que incluye otro objeto anidado dentro de él. Puede modificar las propiedades de este objeto anidado de la misma manera que modificó las propiedades en el último desafío. Establezca el valor de la clave en online en 45 . +
+ +## Tests +
+ +```yml +tests: + - text: ' userActivity tiene id , date y propiedades de data ' + testString: 'assert("id" in userActivity && "date" in userActivity && "data" in userActivity, "userActivity has id, date and data properties");' + - text: userActivity tiene una clave de data configurada para un objeto con las teclas totalUsers y en online + testString: 'assert("totalUsers" in userActivity.data && "online" in userActivity.data, "userActivity has a data key set to an object with keys totalUsers and online");' + - text: La propiedad en online anidada en la clave de data de userActivity debe establecer en 45 + testString: 'assert(userActivity.data.online === 45, "The online property nested in the data key of userActivity should be set to 45");' + - text: La propiedad en online se establece mediante notación de punto o corchete + testString: 'assert.strictEqual(code.search(/online: 45/), -1, "The online property is set using dot or bracket notation");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let userActivity = { + id: 23894201352, + date: 'January 1, 2017', + data: { + totalUsers: 51, + online: 42 + } +}; + +// change code below this line + +// change code above this line + +console.log(userActivity); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.spanish.md new file mode 100644 index 0000000000..2b04ce4061 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-from-an-array-with-pop-and-shift.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d78b2367417b2b2512b0f +title: Remove Items from an Array with pop() and shift() +localeTitle: Eliminar elementos de una matriz con pop () y shift () +challengeType: 1 +--- + +## Description +
+Tanto push() como unshift() tienen métodos correspondientes que son opuestos casi funcionales: pop() y shift() . Como ya habrá adivinado, en lugar de agregar, pop() elimina un elemento del final de una matriz, mientras que shift() elimina un elemento desde el principio. La diferencia clave entre pop() y shift() y sus primos push() y unshift() , es que ninguno de los dos métodos toma parámetros, y cada uno solo permite que una matriz sea modificada por un solo elemento a la vez. +Echemos un vistazo: +
let greetings = ['whats up?', 'hello', 'see ya!'];

greetings.pop();
// now equals ['whats up?', 'hello']

greetings.shift();
// now equals ['hello']
+También podemos devolver el valor del elemento eliminado con uno de estos métodos: +
let popped = greetings.pop();
// returns 'hello'
// greetings now equals []
+
+ +## Instructions +
+Hemos definido una función, popShift , que toma una matriz como argumento y devuelve una nueva matriz. Modifique la función, utilizando pop() y shift() , para eliminar el primer y último elemento de la matriz de argumentos, y asigne los elementos eliminados a sus variables correspondientes, de modo que la matriz devuelta contenga sus valores. +
+ +## Tests +
+ +```yml +tests: + - text: ' popShift(["challenge", "is", "not", "complete"]) debe devolver ["challenge", "complete"] ' + testString: 'assert.deepEqual(popShift(["challenge", "is", "not", "complete"]), ["challenge", "complete"], "popShift(["challenge", "is", "not", "complete"]) should return ["challenge", "complete"]");' + - text: La función popShift debería utilizar el método pop() + testString: 'assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1, "The popShift function should utilize the pop() method");' + - text: La función popShift debería utilizar el método shift() + testString: 'assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1, "The popShift function should utilize the shift() method");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function popShift(arr) { + let popped; // change this line + let shifted; // change this line + return [shifted, popped]; +} + +// do not change code below this line +console.log(popShift(['challenge', 'is', 'not', 'complete'])); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.spanish.md new file mode 100644 index 0000000000..364673f6a1 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/remove-items-using-splice.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d78b2367417b2b2512b10 +title: Remove Items Using splice() +localeTitle: Quitar elementos utilizando empalme () +challengeType: 1 +--- + +## Description +
+Bien, hemos aprendido cómo eliminar elementos del principio y el final de los arreglos usando shift() y pop() , pero ¿qué pasa si queremos eliminar un elemento de algún lugar en el medio? ¿O eliminar más de un elemento a la vez? Bueno, ahí es donde entra splice() . splice() nos permite hacer precisamente eso: eliminar cualquier número de elementos consecutivos de cualquier lugar en una matriz. +splice() puede tomar hasta 3 parámetros, pero por ahora, nos enfocaremos solo en los primeros 2. Los primeros dos parámetros de splice() son enteros que representan índices, o posiciones, de la matriz que splice() es siendo llamado. Y recuerde, las matrices tienen un índice de cero , por lo que para indicar el primer elemento de una matriz, usaríamos 0 . El primer parámetro de splice() representa el índice en la matriz a partir de la cual comenzar a eliminar elementos, mientras que el segundo parámetro indica el número de elementos a eliminar. Por ejemplo: +
let array = ['today', 'was', 'not', 'so', 'great'];

array.splice(2, 2);
// remove 2 elements beginning with the 3rd element
// array now equals ['today', 'was', 'great']
+splice() no solo modifica la matriz en la que se llama, sino que también devuelve una nueva matriz que contiene el valor de los elementos eliminados: +
let array = ['I', 'am', 'feeling', 'really', 'happy'];

let newArray = array.splice(3, 2);
// newArray equals ['really', 'happy']
+
+ +## Instructions +
+Hemos definido una función, sumOfTen , que toma una matriz como argumento y devuelve la suma de los elementos de esa matriz. Modifique la función, usando splice() , para que devuelva un valor de 10 . +
+ +## Tests +
+ +```yml +tests: + - text: sumOfTen debe devolver 10 + testString: 'assert.strictEqual(sumOfTen([2, 5, 1, 5, 2, 1]), 10, "sumOfTen should return 10");' + - text: La función sumOfTen debe utilizar el método splice() + testString: 'assert.notStrictEqual(sumOfTen.toString().search(/\.splice\(/), -1, "The sumOfTen function should utilize the splice() method");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function sumOfTen(arr) { + // change code below this line + + // change code above this line + return arr.reduce((a, b) => a + b); +} + +// do not change code below this line +console.log(sumOfTen([2, 5, 1, 5, 2, 1])); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.spanish.md new file mode 100644 index 0000000000..be817798a2 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-an-array-to-store-a-collection-of-data.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7b7e367417b2b2512b20 +title: Use an Array to Store a Collection of Data +localeTitle: Utilice una matriz para almacenar una colección de datos +challengeType: 1 +--- + +## Description +
+A continuación se muestra un ejemplo de la implementación más simple de una estructura de datos de matriz. Esto se conoce como una matriz unidimensional , lo que significa que solo tiene un nivel, o que no tiene ninguna otra matriz anidada dentro de ella. Observe que contiene valores booleanos , cadenas y números , entre otros tipos de datos de JavaScript válidos: +
let simpleArray = ['one', 2, 'three’, true, false, undefined, null];
console.log(simpleArray.length);
// logs 7
+Todas las matrices tienen una propiedad de longitud que, como se muestra arriba, se puede acceder muy fácilmente con la sintaxis Array.length . +Una implementación más compleja de una matriz se puede ver a continuación. Esto se conoce como una matriz multidimensional o una matriz que contiene otras matrices. Tenga en cuenta que esta matriz también contiene objetos JavaScript, que examinaremos detenidamente en nuestra próxima sección, pero por ahora, todo lo que necesita saber es que las matrices también son capaces de almacenar objetos complejos. +
let complexArray = [
  [
    {
      one: 1,
      two: 2
    },
    {
      three: 3,
      four: 4
    }
  ],
  [
    {
      a: "a",
      b: "b"
    },
    {
      c: "c",
      d: “d”
    }
  ]
];
+
+ +## Instructions +
+Hemos definido una variable llamada yourArray . Complete la declaración asignando una matriz de al menos 5 elementos de longitud a la variable yourArray . Su matriz debe contener al menos una cadena , un número y un booleano . +
+ +## Tests +
+ +```yml +tests: + - text: yourArray es una matriz + testString: 'assert.strictEqual(Array.isArray(yourArray), true, "yourArray is an array");' + - text: yourArray tiene al menos 5 elementos + testString: 'assert.isAtLeast(yourArray.length, 5, "yourArray is at least 5 elements long");' + - text: yourArray contiene al menos un boolean + testString: 'assert(yourArray.filter( el => typeof el === "boolean").length >= 1, "yourArray contains at least one boolean");' + - text: yourArray contiene al menos un number + testString: 'assert(yourArray.filter( el => typeof el === "number").length >= 1, "yourArray contains at least one number");' + - text: yourArray contiene al menos una string + testString: 'assert(yourArray.filter( el => typeof el === "string").length >= 1, "yourArray contains at least one string");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let yourArray; // change this line +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties.spanish.md new file mode 100644 index 0000000000..7774f539c0 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-data-structures/use-the-delete-keyword-to-remove-object-properties.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b7c367417b2b2512b1b +title: Use the delete Keyword to Remove Object Properties +localeTitle: Utilice la palabra clave delete para eliminar las propiedades del objeto +challengeType: 1 +--- + +## Description +
+Ahora ya sabes qué son los objetos y sus características y ventajas básicas. En resumen, son tiendas de valor clave que proporcionan una forma flexible e intuitiva de estructurar los datos y proporcionan un tiempo de búsqueda muy rápido. A lo largo del resto de estos desafíos, describiremos varias operaciones comunes que puede realizar en objetos para que pueda sentirse cómodo aplicando estas estructuras de datos útiles en sus programas. +En desafíos anteriores, hemos agregado y modificado los pares clave-valor de un objeto. Aquí veremos cómo podemos eliminar un par clave-valor de un objeto. +Repasemos nuestro ejemplo de objeto de foods una última vez. Si quisiéramos eliminar la clave de las apples , podemos eliminarla usando la palabra clave delete así: +
delete foods.apples;
+
+ +## Instructions +
+Use la palabra clave delete para eliminar las teclas de oranges , plums y strawberries del objeto de foods . +
+ +## Tests +
+ +```yml +tests: + - text: 'El objeto de foods solo tiene tres claves: apples , grapes y bananas ' + testString: 'assert(!foods.hasOwnProperty("oranges") && !foods.hasOwnProperty("plums") && !foods.hasOwnProperty("strawberries") && Object.keys(foods).length === 3, "The foods object only has three keys: apples, grapes, and bananas");' + - text: 'Las claves de oranges , plums y strawberries se eliminan usando delete ' + testString: 'assert(code.search(/oranges:/) !== -1 && code.search(/plums:/) !== -1 && code.search(/strawberries:/) !== -1, "The oranges, plums, and strawberries keys are removed using delete");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let foods = { + apples: 25, + oranges: 32, + plums: 28, + bananas: 13, + grapes: 35, + strawberries: 27 +}; + +// change code below this line + +// change code above this line + +console.log(foods); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.spanish.md new file mode 100644 index 0000000000..a6e0016edd --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-array-data-with-indexes.spanish.md @@ -0,0 +1,77 @@ +--- +id: 56bbb991ad1ed5201cd392ca +title: Access Array Data with Indexes +localeTitle: Acceso a datos de matriz con índices +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes' +--- + +## Description +
+Podemos acceder a los datos dentro de las matrices utilizando indexes . +índices de matriz se escriben en la misma notación de corchete que usan las cadenas, excepto que en lugar de especificar un carácter, están especificando una entrada en la matriz. Al igual que las cadenas, las matrices utilizan indización basada en cero , por lo que el primer elemento de una matriz es el elemento 0 . +Ejemplo +
var array = [50,60,70];
array[0]; // equals 50
var data = array[1]; // equals 60
+Nota
No debe haber espacios entre el nombre de la matriz y los corchetes, como la array [0] . Aunque JavaScript puede procesar esto correctamente, esto puede confundir a otros programadores que leen su código. +
+ +## Instructions +
+Cree una variable llamada myData y myArray para que sea igual al primer valor de myArray usando notación de corchete. +
+ +## Tests +
+ +```yml +tests: + - text: La variable myData debe ser igual al primer valor de myArray . + testString: 'assert((function(){if(typeof myArray !== "undefined" && typeof myData !== "undefined" && myArray[0] === myData){return true;}else{return false;}})(), "The variable myData should equal the first value of myArray.");' + - text: Se debe acceder a los datos en la variable myArray usando notación de corchetes. + testString: 'assert((function(){if(code.match(/\s*=\s*myArray\[0\]/g)){return true;}else{return false;}})(), "The data in variable myArray should be accessed using bracket notation.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = [50,60,70]; +var ourData = ourArray[0]; // equals 50 + +// Setup +var myArray = [50,60,70]; + +// Only change code below this line. + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [50,60,70]; +var myData = myArray[0]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.spanish.md new file mode 100644 index 0000000000..5c561c9511 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/access-multi-dimensional-arrays-with-indexes.spanish.md @@ -0,0 +1,73 @@ +--- +id: 56592a60ddddeae28f7aa8e1 +title: Access Multi-Dimensional Arrays With Indexes +localeTitle: Acceder a matrices multidimensionales con índices +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes' +--- + +## Description +
+Una forma de pensar en una matriz multidimensional es como una matriz de matrices . Cuando usa corchetes para acceder a su matriz, el primer conjunto de corchetes se refiere a las entradas en la matriz más externa (el primer nivel), y cada par adicional de corchetes se refiere al siguiente nivel de entradas adentro. +Ejemplo +
var arr = [
  [1,2,3],
  [4,5,6],
  [7,8,9],
  [[10,11,12], 13, 14]
];
arr[3]; // equals [[10,11,12], 13, 14]
arr[3][0]; // equals [10,11,12]
arr[3][0][1]; // equals 11
+Nota
No debe haber espacios entre el nombre de la matriz y los corchetes, como la array [0][0] e incluso esta array [0] [0] no está permitida. Aunque JavaScript puede procesar esto correctamente, esto puede confundir a otros programadores que leen su código. +
+ +## Instructions +
+Usando la notación de corchetes, seleccione un elemento de myArray para que myData sea ​​igual a 8 . +
+ +## Tests +
+ +```yml +tests: + - text: myData debe ser igual a 8 . + testString: 'assert(myData === 8, "myData should be equal to 8.");' + - text: Debe usar la notación de corchetes para leer el valor correcto de myArray . + testString: 'assert(/myArray\[2\]\[1\]/g.test(code) && !/myData\s*=\s*(?:.*[-+*/%]|\d)/g.test(code), "You should be using bracket notation to read the correct value from myArray.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myArray = [[1,2,3], [4,5,6], [7,8,9], [[10,11,12], 13, 14]]; + +// Only change code below this line. +var myData = myArray[0][0]; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [[1,2,3],[4,5,6], [7,8,9], [[10,11,12], 13, 14]]; +var myData = myArray[2][1]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.spanish.md new file mode 100644 index 0000000000..3f03f42582 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-arrays.spanish.md @@ -0,0 +1,110 @@ +--- +id: 56533eb9ac21ba0edf2244cd +title: Accessing Nested Arrays +localeTitle: Acceso a matrices anidadas +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/access-array-data-with-indexes' +--- + +## Description +
+Como hemos visto en ejemplos anteriores, los objetos pueden contener tanto objetos anidados como matrices anidadas. Al igual que para acceder a objetos anidados, la notación de paréntesis de arrays se puede encadenar para acceder a arrays anidados. +Aquí hay un ejemplo de cómo acceder a una matriz anidada: +
var ourPets = [
  {
    animalType: "cat",
    names: [
      "Meowzer",
      "Fluffy",
      "Kit-Cat"
    ]
  },
  {
    animalType: "dog",
    names: [
      "Spot",
      "Bowser",
      "Frankie"
    ]
  }
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
+
+ +## Instructions +
+Recupere el segundo árbol de la variable myPlants usando el punto de objeto y la notación de corchete de matriz. +
+ +## Tests +
+ +```yml +tests: + - text: secondTree debe ser igual a "pino" + testString: 'assert(secondTree === "pine", "secondTree should equal "pine"");' + - text: Use la notación de puntos y corchetes para acceder a myPlants + testString: 'assert(/=\s*myPlants\[1\].list\[1\]/.test(code), "Use dot and bracket notation to access myPlants");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myPlants = [ + { + type: "flowers", + list: [ + "rose", + "tulip", + "dandelion" + ] + }, + { + type: "trees", + list: [ + "fir", + "pine", + "birch" + ] + } +]; + +// Only change code below this line + +var secondTree = ""; // Change this line + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myPlants = [ + { + type: "flowers", + list: [ + "rose", + "tulip", + "dandelion" + ] + }, + { + type: "trees", + list: [ + "fir", + "pine", + "birch" + ] + } +]; + +// Only change code below this line + +var secondTree = myPlants[1].list[1]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.spanish.md new file mode 100644 index 0000000000..e505fdaf27 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-nested-objects.spanish.md @@ -0,0 +1,91 @@ +--- +id: 56533eb9ac21ba0edf2244cc +title: Accessing Nested Objects +localeTitle: Accediendo a objetos anidados +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-nested-objects-in-json' +--- + +## Description +
+Se puede acceder a las sub-propiedades de los objetos encadenando la notación de punto o corchete. +Aquí hay un objeto anidado: +
var ourStorage = {
  "desk": {
    "drawer": "stapler"
  },
  "cabinet": {
    "top drawer": {
      "folder1": "a file",
      "folder2": "secrets"
    },
    "bottom drawer": "soda"
  }
};
ourStorage.cabinet["top drawer"].folder2; // "secrets"
ourStorage.desk.drawer; // "stapler"
+
+ +## Instructions +
+Acceda al objeto myStorage y asigne el contenido de la propiedad de la glove box a la variable gloveBoxContents . Utilice la notación de corchete para las propiedades con un espacio en su nombre. +
+ +## Tests +
+ +```yml +tests: + - text: gloveBoxContents debe ser igual a "mapas" + testString: 'assert(gloveBoxContents === "maps", "gloveBoxContents should equal "maps"");' + - text: Usa la notación de puntos y corchetes para acceder a myStorage + testString: 'assert(/=\s*myStorage\.car\.inside\[\s*("|")glove box\1\s*\]/g.test(code), "Use dot and bracket notation to access myStorage");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myStorage = { + "car": { + "inside": { + "glove box": "maps", + "passenger seat": "crumbs" + }, + "outside": { + "trunk": "jack" + } + } +}; + +var gloveBoxContents = undefined; // Change this line + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myStorage = { + "car":{ + "inside":{ + "glove box":"maps", + "passenger seat":"crumbs" + }, + "outside":{ + "trunk":"jack" + } + } +}; +var gloveBoxContents = myStorage.car.inside["glove box"]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.spanish.md new file mode 100644 index 0000000000..9f3f823d4f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation.spanish.md @@ -0,0 +1,90 @@ +--- +id: 56533eb9ac21ba0edf2244c8 +title: Accessing Object Properties with Bracket Notation +localeTitle: Acceso a las propiedades del objeto con notación de corchete +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-objects-properties-with-bracket-notation' +--- + +## Description +
+La segunda forma de acceder a las propiedades de un objeto es la notación de corchetes ( [] ). Si la propiedad del objeto al que intenta acceder tiene un espacio en su nombre, deberá utilizar la notación de corchetes. +Sin embargo, aún puede usar la notación de corchete en las propiedades del objeto sin espacios. +Aquí hay una muestra del uso de la notación de corchetes para leer la propiedad de un objeto: +
var myObj = {
  "Space Name": "Kirk",
  "More Space": "Spock",
  "NoSpace": "USS Enterprise"
};
myObj["Space Name"]; // Kirk
myObj['More Space']; // Spock
myObj["NoSpace"]; // USS Enterprise
+Tenga en cuenta que los nombres de propiedades con espacios en ellos deben estar entre comillas (simple o doble). +
+ +## Instructions +
+Lea los valores de las propiedades "an entree" y "the drink" de testObj utilizando la notación de corchetes y asignarlos a entreeValue y drinkValue respectivamente. +
+ +## Tests +
+ +```yml +tests: + - text: entreeValue debe ser una cadena + testString: 'assert(typeof entreeValue === "string" , "entreeValue should be a string");' + - text: El valor de entreeValue debe ser "hamburger" + testString: 'assert(entreeValue === "hamburger" , "The value of entreeValue should be "hamburger"");' + - text: drinkValue debe ser una cadena + testString: 'assert(typeof drinkValue === "string" , "drinkValue should be a string");' + - text: El valor de drinkValue debe ser "water" + testString: 'assert(drinkValue === "water" , "The value of drinkValue should be "water"");' + - text: Usted debe usar la notación de soporte dos veces + testString: 'assert(code.match(/testObj\s*?\[("|")[^""]+\1\]/g).length > 1, "You should use bracket notation twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var testObj = { + "an entree": "hamburger", + "my side": "veggies", + "the drink": "water" +}; + +// Only change code below this line + +var entreeValue = testObj; // Change this line +var drinkValue = testObj; // Change this line +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var testObj = { + "an entree": "hamburger", + "my side": "veggies", + "the drink": "water" +}; +var entreeValue = testObj["an entree"]; +var drinkValue = testObj['the drink']; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.spanish.md new file mode 100644 index 0000000000..d46a79eb90 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation.spanish.md @@ -0,0 +1,89 @@ +--- +id: 56533eb9ac21ba0edf2244c7 +title: Accessing Object Properties with Dot Notation +localeTitle: Acceso a las propiedades del objeto con notación de puntos +challengeType: 1 +--- + +## Description +
+Hay dos formas de acceder a las propiedades de un objeto: notación de puntos ( . ) Y notación de corchetes ( [] ), similar a una matriz. +notación de puntos es lo que usa cuando conoce el nombre de la propiedad a la que intenta acceder con anticipación. +Aquí hay una muestra de cómo usar la notación de puntos ( . ) Para leer la propiedad de un objeto: +
var myObj = {
  prop1: "val1",
  prop2: "val2"
};
var prop1val = myObj.prop1; // val1
var prop2val = myObj.prop2; // val2
+
+ +## Instructions +
+Lea los valores de propiedad de testObj usando la notación de puntos. Establezca la variable hatValue igual al hat propiedad del objeto y establezca la variable shirtValue igual a la shirt propiedad del objeto. +
+ +## Tests +
+ +```yml +tests: + - text: hatValue debe ser una cadena + testString: 'assert(typeof hatValue === "string" , "hatValue should be a string");' + - text: El valor de hatValue debe ser "ballcap" + testString: 'assert(hatValue === "ballcap" , "The value of hatValue should be "ballcap"");' + - text: shirtValue debe ser una cadena + testString: 'assert(typeof shirtValue === "string" , "shirtValue should be a string");' + - text: El valor de shirtValue debe ser "jersey" + testString: 'assert(shirtValue === "jersey" , "The value of shirtValue should be "jersey"");' + - text: Deberías usar la notación de puntos dos veces. + testString: 'assert(code.match(/testObj\.\w+/g).length > 1, "You should use dot notation twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var testObj = { + "hat": "ballcap", + "shirt": "jersey", + "shoes": "cleats" +}; + +// Only change code below this line + +var hatValue = testObj; // Change this line +var shirtValue = testObj; // Change this line +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var testObj = { + "hat": "ballcap", + "shirt": "jersey", + "shoes": "cleats" +}; + +var hatValue = testObj.hat; +var shirtValue = testObj.shirt; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.spanish.md new file mode 100644 index 0000000000..bf19f89a6d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.spanish.md @@ -0,0 +1,95 @@ +--- +id: 56533eb9ac21ba0edf2244c9 +title: Accessing Object Properties with Variables +localeTitle: Accediendo a las propiedades del objeto con variables +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/accessing-objects-properties-with-variables' +--- + +## Description +
+Otro uso de la notación de corchetes en los objetos es acceder a una propiedad que se almacena como el valor de una variable. Esto puede ser muy útil para iterar a través de las propiedades de un objeto o al acceder a una tabla de búsqueda. +Aquí hay un ejemplo del uso de una variable para acceder a una propiedad: +
var dogs = {
  Fido: "Mutt", + Hunter: "Doberman", + Snoopie: "Beagle"
};
var myDog = "Hunter";
var myBreed = dogs[myDog];
console.log(myBreed); // "Doberman"
+Otra forma en que puede usar este concepto es cuando el nombre de la propiedad se recopila dinámicamente durante la ejecución del programa, de la siguiente manera: +
var someObj = {
  propName: "John"
};
function propPrefix(str) {
  var s = "prop";
  return s + str;
}
var someProp = propPrefix("Name"); // someProp now holds the value 'propName'
console.log(someObj[someProp]); // "John"
+Tenga en cuenta que no usamos comillas alrededor del nombre de la variable cuando la usamos para acceder a la propiedad porque estamos usando el valor de la variable, no el nombre . +
+ +## Instructions +
+Use la variable playerNumber para buscar el jugador 16 en testObj usando la notación de corchete. Luego asigna ese nombre a la variable del player . +
+ +## Tests +
+ +```yml +tests: + - text: playerNumber debería ser un número + testString: 'assert(typeof playerNumber === "number", "playerNumber should be a number");' + - text: El player variable debe ser una cadena. + testString: 'assert(typeof player === "string", "The variable player should be a string");' + - text: El valor del player debe ser "Montana". + testString: 'assert(player === "Montana", "The value of player should be "Montana"");' + - text: Debe usar la notación de corchetes para acceder a testObj + testString: 'assert(/testObj\s*?\[.*?\]/.test(code),"You should use bracket notation to access testObj");' + - text: No debes asignar el valor Montana al player variable directamente. + testString: 'assert(!code.match(/player\s*=\s*"|\"\s*Montana\s*"|\"\s*;/gi),"You should not assign the value Montana to the variable player directly.");' + - text: Debería usar la variable playerNumber en su notación de corchete + testString: 'assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code),"You should be using the variable playerNumber in your bracket notation");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var testObj = { + 12: "Namath", + 16: "Montana", + 19: "Unitas" +}; + +// Only change code below this line; + +var playerNumber; // Change this Line +var player = testObj; // Change this Line +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var testObj = { + 12: "Namath", + 16: "Montana", + 19: "Unitas" +}; +var playerNumber = 16; +var player = testObj[playerNumber]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.spanish.md new file mode 100644 index 0000000000..a32cd9e631 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-new-properties-to-a-javascript-object.spanish.md @@ -0,0 +1,93 @@ +--- +id: 56bbb991ad1ed5201cd392d2 +title: Add New Properties to a JavaScript Object +localeTitle: Agregar nuevas propiedades a un objeto de JavaScript +challengeType: 1 +--- + +## Description +
+Puede agregar nuevas propiedades a los objetos JavaScript existentes de la misma manera que los modificaría. +Así es como agregaríamos una propiedad de "bark" a ourDog : +ourDog.bark = "bow-wow"; +o +ourDog["bark"] = "bow-wow"; +Ahora, cuando evaluamos ourDog.bark , obtendremos su ladrido, "bow-wow". +
+ +## Instructions +
+Agrega una propiedad de "bark" a myDog y myDog con un sonido de perro, como "woof". Puede usar la notación de punto o corchete. +
+ +## Tests +
+ +```yml +tests: + - text: Agregue la propiedad "bark" a myDog . + testString: 'assert(myDog.bark !== undefined, "Add the property "bark" to myDog.");' + - text: No agregue "bark" a la sección de configuración + testString: 'assert(!/bark[^\n]:/.test(code), "Do not add "bark" to the setup section");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"] +}; + +ourDog.bark = "bow-wow"; + +// Setup +var myDog = { + "name": "Happy Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"] +}; + +// Only change code below this line. + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myDog = { + "name": "Happy Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"] +}; +myDog.bark = "Woof Woof"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.spanish.md new file mode 100644 index 0000000000..7dcf00bc26 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/add-two-numbers-with-javascript.spanish.md @@ -0,0 +1,68 @@ +--- +id: cf1111c1c11feddfaeb3bdef +title: Add Two Numbers with JavaScript +localeTitle: Añadir dos números con JavaScript +challengeType: 1 +--- + +## Description +
+Number es un tipo de datos en JavaScript que representa datos numéricos. +Ahora vamos a tratar de sumar dos números usando JavaScript. +JavaScript usa el símbolo + como operación de suma cuando se coloca entre dos números. +Ejemplo +
myVar = 5 + 10; // assigned 15
+
+ +## Instructions +
+Cambia el 0 para que la suma sea igual a 20 . +
+ +## Tests +
+ +```yml +tests: + - text: sum debe ser igual a 20 + testString: 'assert(sum === 20, "sum should equal 20");' + - text: Usa el operador + + testString: 'assert(/\+/.test(code), "Use the + operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var sum = 10 + 0; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var sum = 10 + 10; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.spanish.md new file mode 100644 index 0000000000..b6d5e2d88a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/adding-a-default-option-in-switch-statements.spanish.md @@ -0,0 +1,99 @@ +--- +id: 56533eb9ac21ba0edf2244de +title: Adding a Default Option in Switch Statements +localeTitle: Adición de una opción predeterminada en los estados de cambio +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/adding-a-default-option-in-switch-statements' +--- + +## Description +
+En una declaración de switch , es posible que no pueda especificar todos los valores posibles como declaraciones de case . En su lugar, puede agregar la declaración default que se ejecutará si no se encuentran declaraciones de case coincidentes. Piense en ello como la última instrucción else en una cadena if/else . +Una declaración por default debe ser el último caso. +
switch (num) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
...
  default:
    defaultStatement;
    break;
}
+
+ +## Instructions +
+Escriba una instrucción de cambio para establecer la answer para las siguientes condiciones:
"a" - "manzana"
"b" - "pájaro"
"c" - "gato"
default - "cosas" +
+ +## Tests +
+ +```yml +tests: + - text: switchOfStuff("a") debe tener un valor de "apple" + testString: 'assert(switchOfStuff("a") === "apple", "switchOfStuff("a") should have a value of "apple"");' + - text: switchOfStuff("b") debe tener un valor de "bird" + testString: 'assert(switchOfStuff("b") === "bird", "switchOfStuff("b") should have a value of "bird"");' + - text: switchOfStuff("c") debe tener un valor de "cat" + testString: 'assert(switchOfStuff("c") === "cat", "switchOfStuff("c") should have a value of "cat"");' + - text: switchOfStuff("d") debe tener un valor de "cosas" + testString: 'assert(switchOfStuff("d") === "stuff", "switchOfStuff("d") should have a value of "stuff"");' + - text: switchOfStuff(4) debe tener un valor de "cosas" + testString: 'assert(switchOfStuff(4) === "stuff", "switchOfStuff(4) should have a value of "stuff"");' + - text: No debes usar ninguna declaración if o else + testString: 'assert(!/else/g.test(code) || !/if/g.test(code), "You should not use any if or else statements");' + - text: Debes usar una declaración por default + testString: 'assert(switchOfStuff("string-to-trigger-default-case") === "stuff", "You should use a default statement");' + - text: Debe tener al menos 3 declaraciones de break + testString: 'assert(code.match(/break/g).length > 2, "You should have at least 3 break statements");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function switchOfStuff(val) { + var answer = ""; + // Only change code below this line + + + + // Only change code above this line + return answer; +} + +// Change this value to test +switchOfStuff(1); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function switchOfStuff(val) { + var answer = ""; + + switch(val) { + case "a": + answer = "apple"; + break; + case "b": + answer = "bird"; + break; + case "c": + answer = "cat"; + break; + default: + answer = "stuff"; + } + return answer; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.spanish.md new file mode 100644 index 0000000000..3010681f21 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/appending-variables-to-strings.spanish.md @@ -0,0 +1,79 @@ +--- +id: 56533eb9ac21ba0edf2244ed +title: Appending Variables to Strings +localeTitle: Anexando Variables a las Cadenas +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/appending-variables-to-strings' +--- + +## Description +
+Al igual que podemos construir una cadena sobre varias líneas a partir de literales de cadena, también podemos agregar variables a una cadena usando el operador más es igual a ( += ). +
+ +## Instructions +
+Establezca someAdjective y someAdjective a myStr usando el operador += . +
+ +## Tests +
+ +```yml +tests: + - text: someAdjective debe establecerse en una cadena de al menos 3 caracteres de largo + testString: 'assert(typeof someAdjective !== "undefined" && someAdjective.length > 2, "someAdjective should be set to a string at least 3 characters long");' + - text: someAdjective de someAdjective a myStr usando el operador += + testString: 'assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0, "Append someAdjective to myStr using the += operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var anAdjective = "awesome!"; +var ourStr = "freeCodeCamp is "; +ourStr += anAdjective; + +// Only change code below this line + +var someAdjective; +var myStr = "Learning to code is "; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var anAdjective = "awesome!"; +var ourStr = "freeCodeCamp is "; +ourStr += anAdjective; + +var someAdjective = "neat"; +var myStr = "Learning to code is "; +myStr += someAdjective; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.spanish.md new file mode 100644 index 0000000000..8421341c50 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.spanish.md @@ -0,0 +1,91 @@ +--- +id: 56533eb9ac21ba0edf2244c3 +title: Assignment with a Returned Value +localeTitle: Asignación con un valor devuelto +challengeType: 1 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/assignment-with-a-returned-value' +--- + +## Description +
+Si recordará de nuestra discusión sobre el almacenamiento de valores con el operador de asignación , todo a la derecha del signo igual se resuelve antes de que se asigne el valor. Esto significa que podemos tomar el valor de retorno de una función y asignarlo a una variable. +Supongamos que hemos predefinido una sum función que suma dos números, luego: +ourSum = sum(5, 12); +llamará a la función sum , que devuelve un valor de 17 y lo asigna a ourSum variable ourSum . +
+ +## Instructions +
+Llame a la función processArg con un argumento de 7 y asigne su valor de retorno a la variable processed . +
+ +## Tests +
+ +```yml +tests: + - text: processed debe tener un valor de 2 + testString: 'assert(processed === 2, "processed should have a value of 2");' + - text: Debes asignar processArg a processed + testString: 'assert(/processed\s*=\s*processArg\(\s*7\s*\)\s*;/.test(code), "You should assign processArg to processed");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var changed = 0; + +function change(num) { + return (num + 5) / 3; +} + +changed = change(10); + +// Setup +var processed = 0; + +function processArg(num) { + return (num + 3) / 5; +} + +// Only change code below this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var processed = 0; + +function processArg(num) { + return (num + 3) / 5; +} + +processed = processArg(7); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.spanish.md new file mode 100644 index 0000000000..9669385d46 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/build-javascript-objects.spanish.md @@ -0,0 +1,97 @@ +--- +id: 56bbb991ad1ed5201cd392d0 +title: Build JavaScript Objects +localeTitle: Construir objetos de JavaScript +challengeType: 1 +--- + +## Description +
+Es posible que hayas escuchado el término object antes. +objetos son similares a las arrays , excepto que en lugar de utilizar índices para acceder y modificar sus datos, puede acceder a los datos en objetos a través de lo que se denomina properties . +objetos son útiles para almacenar datos de manera estructurada y pueden representar objetos del mundo real, como un gato. +Aquí hay una muestra de un objeto de gato: +
var cat = {
  "name": "Whiskers",
  "legs": 4,
  "tails": 1,
  "enemies": ["Water", "Dogs"]
};
+En este ejemplo, todas las propiedades se almacenan como cadenas, como "name" , "legs" y "tails" . Sin embargo, también puede utilizar los números como propiedades. Incluso puede omitir las comillas para las propiedades de cadena de una sola palabra, de la siguiente manera: +
var anotherObject = {
  make: "Ford",
  5: "five",
  "model": "focus"
};
+Sin embargo, si su objeto tiene propiedades que no son de cadena, JavaScript las encasillará automáticamente como cadenas. +
+ +## Instructions +
+Haz un objeto que represente un perro llamado myDog que contenga las propiedades "name" (una cadena), "legs" , "tails" y "friends" . +Puede establecer estas propiedades de objeto en los valores que desee, siempre que "name" sea ​​una cadena, "legs" y "tails" sean números, y "friends" es una matriz. +
+ +## Tests +
+ +```yml +tests: + - text: myDog debe contener el name la propiedad y debe ser una string . + testString: 'assert((function(z){if(z.hasOwnProperty("name") && z.name !== undefined && typeof z.name === "string"){return true;}else{return false;}})(myDog), "myDog should contain the property name and it should be a string.");' + - text: myDog debe contener las legs propiedad y debe ser un number . + testString: 'assert((function(z){if(z.hasOwnProperty("legs") && z.legs !== undefined && typeof z.legs === "number"){return true;}else{return false;}})(myDog), "myDog should contain the property legs and it should be a number.");' + - text: myDog debe contener las tails propiedad y debe ser un number . + testString: 'assert((function(z){if(z.hasOwnProperty("tails") && z.tails !== undefined && typeof z.tails === "number"){return true;}else{return false;}})(myDog), "myDog should contain the property tails and it should be a number.");' + - text: myDog debe contener los friends la propiedad y debe ser una array . + testString: 'assert((function(z){if(z.hasOwnProperty("friends") && z.friends !== undefined && Array.isArray(z.friends)){return true;}else{return false;}})(myDog), "myDog should contain the property friends and it should be an array.");' + - text: myDog solo debe contener todas las propiedades dadas. + testString: 'assert((function(z){return Object.keys(z).length === 4;})(myDog), "myDog should only contain all the given properties.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"] +}; + +// Only change code below this line. + +var myDog = { + + + + +}; +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"] +}; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.spanish.md new file mode 100644 index 0000000000..8e1cee6191 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements.spanish.md @@ -0,0 +1,100 @@ +--- +id: 56533eb9ac21ba0edf2244dc +title: Chaining If Else Statements +localeTitle: Encadenamiento en caso contrario +challengeType: 1 +--- + +## Description +
+if/else sentencias pueden ser encadenadas juntas para lógica compleja. Aquí está el pseudocódigo de múltiples encadenadas if / else if enunciados: +
if ( condition1 ) {
   statement1
} else if ( condition2 ) {
   statement2
} else if ( condition3 ) {
   statement3
. . .
} else {
   statementN
}
+
+ +## Instructions +
+Escribir en cadena if / else if sentencias para cumplir con las siguientes condiciones: +num < 5 - devolver "Tiny"
num < 10 - devuelve "Small"
num < 15 - devuelve "Medio"
num < 20 - devuelve "Large"
num >= 20 - devuelve "Enorme" +
+ +## Tests +
+ +```yml +tests: + - text: Debes tener al menos cuatro declaraciones else + testString: 'assert(code.match(/else/g).length > 3, "You should have at least four else statements");' + - text: Debes tener al menos cuatro if declaraciones + testString: 'assert(code.match(/if/g).length > 3, "You should have at least four if statements");' + - text: Debe tener al menos una declaración de return + testString: 'assert(code.match(/return/g).length >= 1, "You should have at least one return statement");' + - text: testSize(0) debería devolver "Tiny" + testString: 'assert(testSize(0) === "Tiny", "testSize(0) should return "Tiny"");' + - text: testSize(4) debería devolver "Tiny" + testString: 'assert(testSize(4) === "Tiny", "testSize(4) should return "Tiny"");' + - text: testSize(5) debe devolver "Small" + testString: 'assert(testSize(5) === "Small", "testSize(5) should return "Small"");' + - text: testSize(8) debe devolver "Small" + testString: 'assert(testSize(8) === "Small", "testSize(8) should return "Small"");' + - text: testSize(10) debe devolver "Medium" + testString: 'assert(testSize(10) === "Medium", "testSize(10) should return "Medium"");' + - text: testSize(14) debe devolver "Medium" + testString: 'assert(testSize(14) === "Medium", "testSize(14) should return "Medium"");' + - text: testSize(15) debe devolver "Large" + testString: 'assert(testSize(15) === "Large", "testSize(15) should return "Large"");' + - text: testSize(17) debería devolver "Large" + testString: 'assert(testSize(17) === "Large", "testSize(17) should return "Large"");' + - text: testSize(20) debería devolver "Huge" + testString: 'assert(testSize(20) === "Huge", "testSize(20) should return "Huge"");' + - text: testSize(25) debería devolver "Huge" + testString: 'assert(testSize(25) === "Huge", "testSize(25) should return "Huge"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testSize(num) { + // Only change code below this line + + + return "Change Me"; + // Only change code above this line +} + +// Change this value to test +testSize(7); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testSize(num) { + if (num < 5) { + return "Tiny"; + } else if (num < 10) { + return "Small"; + } else if (num < 15) { + return "Medium"; + } else if (num < 20) { + return "Large"; + } else { + return "Huge"; + } +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.spanish.md new file mode 100644 index 0000000000..46b67c8e21 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comment-your-javascript-code.spanish.md @@ -0,0 +1,62 @@ +--- +id: bd7123c9c441eddfaeb4bdef +title: Comment Your JavaScript Code +localeTitle: Comenta tu código JavaScript +challengeType: 1 +--- + +## Description +
+comentarios son líneas de código que JavaScript ignorará intencionalmente. Los comentarios son una excelente manera de dejar notas para usted y para otras personas que más tarde necesitarán averiguar qué hace ese código. +Hay dos formas de escribir comentarios en JavaScript: +Al usar // le indicará a JavaScript que ignore el resto del texto en la línea actual: +
// This is an in-line comment.
+Puede hacer un comentario de varias líneas comenzando con /* y terminando con */ : +
/* This is a
multi-line comment */
+Mejores Prácticas
A medida que escribe el código, debe agregar comentarios regularmente para aclarar la función de partes de su código. Los buenos comentarios pueden ayudar a comunicar la intención de su código, tanto para los demás como para su futuro. +
+ +## Instructions +
+Intenta crear uno de cada tipo de comentario. +
+ +## Tests +
+ +```yml +tests: + - text: Cree un // estilo de comentario que contenga al menos cinco letras. + testString: 'assert(code.match(/(\/\/)...../g), "Create a // style comment that contains at least five letters.");' + - text: Cree un comentario de estilo /* */ que contenga al menos cinco letras. + testString: 'assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm), "Create a /* */ style comment that contains at least five letters.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js + +``` + +
+ + + +
+ +## Solution +
+ + +```js +// Fake Comment +/* Another Comment */ +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.spanish.md new file mode 100644 index 0000000000..4768eb7b01 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator.spanish.md @@ -0,0 +1,78 @@ +--- +id: 56533eb9ac21ba0edf2244d0 +title: Comparison with the Equality Operator +localeTitle: Comparación con el operador de igualdad +challengeType: 1 +--- + +## Description +
+Hay muchos operadores de comparación en JavaScript. Todos estos operadores devuelven un valor true o false booleano. +El operador más básico es el operador de igualdad == . El operador de igualdad compara dos valores y devuelve true si son equivalentes o false si no lo son. Tenga en cuenta que la igualdad es diferente de la asignación ( = ), que asigna el valor a la derecha del operador a una variable en la izquierda. +
function equalityTest(myVal) {
  if (myVal == 10) {
     return "Equal";
  }
  return "Not Equal";
}
+Si myVal es igual a 10 , el operador de igualdad devuelve true , por lo que se ejecutará el código entre llaves y la función devolverá "Equal" . De lo contrario, la función devolverá "Not Equal" . +Para que JavaScript pueda comparar dos data types (por ejemplo, numbers y strings ), debe convertir un tipo a otro. Esto se conoce como "Tipo de coerción". Una vez que lo hace, sin embargo, puede comparar los términos de la siguiente manera: +
1 == 1 // true
1 == 2 // false
1 == '1' // true
"3" == 3 // true
+
+ +## Instructions +
+Agregue el equality operator a la línea indicada para que la función devuelva "Igual" cuando val sea ​​equivalente a 12 +
+ +## Tests +
+ +```yml +tests: + - text: testEqual(10) debe devolver "No es igual" + testString: 'assert(testEqual(10) === "Not Equal", "testEqual(10) should return "Not Equal"");' + - text: testEqual(12) debe devolver "Igual" + testString: 'assert(testEqual(12) === "Equal", "testEqual(12) should return "Equal"");' + - text: testEqual("12") debe devolver "Equal" + testString: 'assert(testEqual("12") === "Equal", "testEqual("12") should return "Equal"");' + - text: Debes usar el operador == + testString: 'assert(code.match(/==/g) && !code.match(/===/g), "You should use the == operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function testEqual(val) { + if (val) { // Change this line + return "Equal"; + } + return "Not Equal"; +} + +// Change this value to test +testEqual(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testEqual(val) { + if (val == 12) { + return "Equal"; + } + return "Not Equal"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-operator.spanish.md new file mode 100644 index 0000000000..adbfb4cee1 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-operator.spanish.md @@ -0,0 +1,91 @@ +--- +id: 56533eb9ac21ba0edf2244d4 +title: Comparison with the Greater Than Operator +localeTitle: Comparación con el operador mayor que +challengeType: 1 +--- + +## Description +
+El operador mayor que ( > ) compara los valores de dos números. Si el número a la izquierda es mayor que el número a la derecha, devuelve true . De lo contrario, devuelve false . +Al igual que el operador de igualdad, el operador mayor que el convertirá los tipos de datos de valores al comparar. +ejemplos +
5 > 3 // true
7 > '3' // true
2 > 3 // false
'1' > 9 // false
+
+ +## Instructions +
+Agregue el operador greater than a las líneas indicadas para que las declaraciones de devolución tengan sentido. +
+ +## Tests +
+ +```yml +tests: + - text: testGreaterThan(0) debe devolver "10 o inferior" + testString: 'assert(testGreaterThan(0) === "10 or Under", "testGreaterThan(0) should return "10 or Under"");' + - text: testGreaterThan(10) debe devolver "10 o inferior" + testString: 'assert(testGreaterThan(10) === "10 or Under", "testGreaterThan(10) should return "10 or Under"");' + - text: testGreaterThan(11) debe devolver "Over 10" + testString: 'assert(testGreaterThan(11) === "Over 10", "testGreaterThan(11) should return "Over 10"");' + - text: testGreaterThan(99) debe devolver "Over 10" + testString: 'assert(testGreaterThan(99) === "Over 10", "testGreaterThan(99) should return "Over 10"");' + - text: testGreaterThan(100) debe devolver "Over 10" + testString: 'assert(testGreaterThan(100) === "Over 10", "testGreaterThan(100) should return "Over 10"");' + - text: testGreaterThan(101) debe devolver "Over 100" + testString: 'assert(testGreaterThan(101) === "Over 100", "testGreaterThan(101) should return "Over 100"");' + - text: testGreaterThan(150) debe devolver "Over 100" + testString: 'assert(testGreaterThan(150) === "Over 100", "testGreaterThan(150) should return "Over 100"");' + - text: Debes usar el operador > al menos dos veces + testString: 'assert(code.match(/val\s*>\s*("|")*\d+("|")*/g).length > 1, "You should use the > operator at least twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testGreaterThan(val) { + if (val) { // Change this line + return "Over 100"; + } + + if (val) { // Change this line + return "Over 10"; + } + + return "10 or Under"; +} + +// Change this value to test +testGreaterThan(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testGreaterThan(val) { + if (val > 100) { // Change this line + return "Over 100"; + } + if (val > 10) { // Change this line + return "Over 10"; + } + return "10 or Under"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.spanish.md new file mode 100644 index 0000000000..a5c7922401 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-greater-than-or-equal-to-operator.spanish.md @@ -0,0 +1,93 @@ +--- +id: 56533eb9ac21ba0edf2244d5 +title: Comparison with the Greater Than Or Equal To Operator +localeTitle: Comparación con el operador mayor o igual que el operador +challengeType: 1 +--- + +## Description +
+El operador greater than or equal to ( >= ) compara los valores de dos números. Si el número a la izquierda es mayor o igual que el número a la derecha, devuelve true . De lo contrario, devuelve false . +Al igual que el operador de igualdad, greater than or equal to operador convertirá los tipos de datos al comparar. +ejemplos +
6 >= 6 // true
7 >= '3' // true
2 >= 3 // false
'7' >= 9 // false
+
+ +## Instructions +
+Agregue el operador greater than or equal to las líneas indicadas para que las declaraciones de devolución tengan sentido. +
+ +## Tests +
+ +```yml +tests: + - text: testGreaterOrEqual(0) debe devolver "Menos de 10" + testString: 'assert(testGreaterOrEqual(0) === "Less than 10", "testGreaterOrEqual(0) should return "Less than 10"");' + - text: testGreaterOrEqual(9) debe devolver "Menos de 10" + testString: 'assert(testGreaterOrEqual(9) === "Less than 10", "testGreaterOrEqual(9) should return "Less than 10"");' + - text: testGreaterOrEqual(10) debe devolver "10 o más" + testString: 'assert(testGreaterOrEqual(10) === "10 or Over", "testGreaterOrEqual(10) should return "10 or Over"");' + - text: testGreaterOrEqual(11) debe devolver "10 o más" + testString: 'assert(testGreaterOrEqual(11) === "10 or Over", "testGreaterOrEqual(11) should return "10 or Over"");' + - text: testGreaterOrEqual(19) debe devolver "10 o más" + testString: 'assert(testGreaterOrEqual(19) === "10 or Over", "testGreaterOrEqual(19) should return "10 or Over"");' + - text: testGreaterOrEqual(100) debe devolver "20 o más" + testString: 'assert(testGreaterOrEqual(100) === "20 or Over", "testGreaterOrEqual(100) should return "20 or Over"");' + - text: testGreaterOrEqual(21) debe devolver "20 o más" + testString: 'assert(testGreaterOrEqual(21) === "20 or Over", "testGreaterOrEqual(21) should return "20 or Over"");' + - text: Debe usar el operador >= al menos dos veces + testString: 'assert(code.match(/val\s*>=\s*("|")*\d+("|")*/g).length > 1, "You should use the >= operator at least twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testGreaterOrEqual(val) { + if (val) { // Change this line + return "20 or Over"; + } + + if (val) { // Change this line + return "10 or Over"; + } + + return "Less than 10"; +} + +// Change this value to test +testGreaterOrEqual(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testGreaterOrEqual(val) { + if (val >= 20) { // Change this line + return "20 or Over"; + } + + if (val >= 10) { // Change this line + return "10 or Over"; + } + + return "Less than 10"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.spanish.md new file mode 100644 index 0000000000..c99cf68388 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-inequality-operator.spanish.md @@ -0,0 +1,79 @@ +--- +id: 56533eb9ac21ba0edf2244d2 +title: Comparison with the Inequality Operator +localeTitle: Comparación con el operador de desigualdad +challengeType: 1 +--- + +## Description +
+El operador de desigualdad ( != ) Es el opuesto del operador de igualdad. Significa "No es igual" y devuelve false donde la igualdad se volvería true y viceversa . Al igual que el operador de igualdad, el operador de desigualdad convertirá los tipos de datos de los valores al comparar. +ejemplos +
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
+
+ +## Instructions +
+Agregue el operador de desigualdad != En la instrucción if para que la función devuelva "No igual" cuando val no es equivalente a 99 +
+ +## Tests +
+ +```yml +tests: + - text: testNotEqual(99) debe devolver "Igual" + testString: 'assert(testNotEqual(99) === "Equal", "testNotEqual(99) should return "Equal"");' + - text: testNotEqual("99") debe devolver "Equal" + testString: 'assert(testNotEqual("99") === "Equal", "testNotEqual("99") should return "Equal"");' + - text: testNotEqual(12) debe devolver "No es igual" + testString: 'assert(testNotEqual(12) === "Not Equal", "testNotEqual(12) should return "Not Equal"");' + - text: testNotEqual("12") debe devolver "Not Equal" + testString: 'assert(testNotEqual("12") === "Not Equal", "testNotEqual("12") should return "Not Equal"");' + - text: testNotEqual("bob") debe devolver "Not Equal" + testString: 'assert(testNotEqual("bob") === "Not Equal", "testNotEqual("bob") should return "Not Equal"");' + - text: Debes usar el operador != + testString: 'assert(code.match(/(?!!==)!=/), "You should use the != operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function testNotEqual(val) { + if (val) { // Change this line + return "Not Equal"; + } + return "Equal"; +} + +// Change this value to test +testNotEqual(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testNotEqual(val) { + if (val != 99) { + return "Not Equal"; + } + return "Equal"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-operator.spanish.md new file mode 100644 index 0000000000..944d34a670 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-operator.spanish.md @@ -0,0 +1,90 @@ +--- +id: 56533eb9ac21ba0edf2244d6 +title: Comparison with the Less Than Operator +localeTitle: Comparación con el operador menor que +challengeType: 1 +--- + +## Description +
+El operador menor que ( < ) compara los valores de dos números. Si el número a la izquierda es menor que el número a la derecha, devuelve true . De lo contrario, devuelve false . Al igual que el operador de igualdad, menos que el operador convierte los tipos de datos al comparar. +ejemplos +
2 < 5 // true
'3' < 7 // true
5 < 5 // false
3 < 2 // false
'8' < 4 // false
+
+ +## Instructions +
+Agregue el operador less than a las líneas indicadas para que las declaraciones de devolución tengan sentido. +
+ +## Tests +
+ +```yml +tests: + - text: testLessThan(0) debe devolver "Under 25" + testString: 'assert(testLessThan(0) === "Under 25", "testLessThan(0) should return "Under 25"");' + - text: testLessThan(24) debe devolver "Under 25" + testString: 'assert(testLessThan(24) === "Under 25", "testLessThan(24) should return "Under 25"");' + - text: testLessThan(25) debe devolver "Under 55" + testString: 'assert(testLessThan(25) === "Under 55", "testLessThan(25) should return "Under 55"");' + - text: testLessThan(54) debe devolver "Under 55" + testString: 'assert(testLessThan(54) === "Under 55", "testLessThan(54) should return "Under 55"");' + - text: testLessThan(55) debería devolver "55 o más" + testString: 'assert(testLessThan(55) === "55 or Over", "testLessThan(55) should return "55 or Over"");' + - text: testLessThan(99) debería devolver "55 o más" + testString: 'assert(testLessThan(99) === "55 or Over", "testLessThan(99) should return "55 or Over"");' + - text: Debes usar el operador < al menos dos veces + testString: 'assert(code.match(/val\s*<\s*("|")*\d+("|")*/g).length > 1, "You should use the < operator at least twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testLessThan(val) { + if (val) { // Change this line + return "Under 25"; + } + + if (val) { // Change this line + return "Under 55"; + } + + return "55 or Over"; +} + +// Change this value to test +testLessThan(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testLessThan(val) { + if (val < 25) { // Change this line + return "Under 25"; + } + + if (val < 55) { // Change this line + return "Under 55"; + } + + return "55 or Over"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.spanish.md new file mode 100644 index 0000000000..09182b14a3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-less-than-or-equal-to-operator.spanish.md @@ -0,0 +1,93 @@ +--- +id: 56533eb9ac21ba0edf2244d7 +title: Comparison with the Less Than Or Equal To Operator +localeTitle: Comparación con el operador menor o igual que +challengeType: 1 +--- + +## Description +
+El operador less than or equal to ( <= ) compara los valores de dos números. Si el número a la izquierda es menor o igual que el número a la derecha, devuelve true . Si el número de la izquierda es mayor que el de la derecha, devuelve false . Al igual que el operador de igualdad, less than or equal to convierte los tipos de datos. +ejemplos +
4 <= 5 // true
'7' <= 7 // true
5 <= 5 // true
3 <= 2 // false
'8' <= 4 // false
+
+ +## Instructions +
+Agregue el operador less than or equal to las líneas indicadas para que las declaraciones de devolución tengan sentido. +
+ +## Tests +
+ +```yml +tests: + - text: testLessOrEqual(0) debe devolver "Más pequeño o igual a 12" + testString: 'assert(testLessOrEqual(0) === "Smaller Than or Equal to 12", "testLessOrEqual(0) should return "Smaller Than or Equal to 12"");' + - text: testLessOrEqual(11) debe devolver "Más pequeño o igual a 12" + testString: 'assert(testLessOrEqual(11) === "Smaller Than or Equal to 12", "testLessOrEqual(11) should return "Smaller Than or Equal to 12"");' + - text: testLessOrEqual(12) debe devolver "Más pequeño o igual a 12" + testString: 'assert(testLessOrEqual(12) === "Smaller Than or Equal to 12", "testLessOrEqual(12) should return "Smaller Than or Equal to 12"");' + - text: testLessOrEqual(23) debe devolver "Más pequeño o igual a 24" + testString: 'assert(testLessOrEqual(23) === "Smaller Than or Equal to 24", "testLessOrEqual(23) should return "Smaller Than or Equal to 24"");' + - text: testLessOrEqual(24) debe devolver "Más pequeño o igual a 24" + testString: 'assert(testLessOrEqual(24) === "Smaller Than or Equal to 24", "testLessOrEqual(24) should return "Smaller Than or Equal to 24"");' + - text: testLessOrEqual(25) debe devolver "Más de 24" + testString: 'assert(testLessOrEqual(25) === "More Than 24", "testLessOrEqual(25) should return "More Than 24"");' + - text: testLessOrEqual(55) debe devolver "Más de 24" + testString: 'assert(testLessOrEqual(55) === "More Than 24", "testLessOrEqual(55) should return "More Than 24"");' + - text: Debe usar el operador <= al menos dos veces + testString: 'assert(code.match(/val\s*<=\s*("|")*\d+("|")*/g).length > 1, "You should use the <= operator at least twice");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testLessOrEqual(val) { + if (val) { // Change this line + return "Smaller Than or Equal to 12"; + } + + if (val) { // Change this line + return "Smaller Than or Equal to 24"; + } + + return "More Than 24"; +} + +// Change this value to test +testLessOrEqual(10); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testLessOrEqual(val) { + if (val <= 12) { // Change this line + return "Smaller Than or Equal to 12"; + } + + if (val <= 24) { // Change this line + return "Smaller Than or Equal to 24"; + } + + return "More Than 24"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.spanish.md new file mode 100644 index 0000000000..3688557fee --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-equality-operator.spanish.md @@ -0,0 +1,77 @@ +--- +id: 56533eb9ac21ba0edf2244d1 +title: Comparison with the Strict Equality Operator +localeTitle: Comparación con el operador de igualdad estricta +challengeType: 1 +--- + +## Description +
+Igualdad estricta ( === ) es la contraparte del operador de igualdad ( == ). Sin embargo, a diferencia del operador de igualdad, que intenta convertir ambos valores en comparación con un tipo común, el operador de igualdad estricta no realiza una conversión de tipo. +Si los valores que se comparan tienen tipos diferentes, se consideran desiguales y el operador de igualdad estricta devolverá el valor falso. +ejemplos +
3 === 3 // true
3 === '3' // false
+En el segundo ejemplo, 3 es un tipo de Number y '3' es un tipo de String . +
+ +## Instructions +
+Use el operador de igualdad estricta en la instrucción if para que la función devuelva "Igual" cuando val sea ​​estrictamente igual a 7 +
+ +## Tests +
+ +```yml +tests: + - text: testStrict(10) debe devolver "No es igual" + testString: 'assert(testStrict(10) === "Not Equal", "testStrict(10) should return "Not Equal"");' + - text: testStrict(7) debe devolver "Igual" + testString: 'assert(testStrict(7) === "Equal", "testStrict(7) should return "Equal"");' + - text: testStrict("7") debe devolver "Not Equal" + testString: 'assert(testStrict("7") === "Not Equal", "testStrict("7") should return "Not Equal"");' + - text: Debes usar el operador === + testString: 'assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0, "You should use the === operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function testStrict(val) { + if (val) { // Change this line + return "Equal"; + } + return "Not Equal"; +} + +// Change this value to test +testStrict(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testStrict(val) { + if (val === 7) { + return "Equal"; + } + return "Not Equal"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-inequality-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-inequality-operator.spanish.md new file mode 100644 index 0000000000..2b1226a31f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-strict-inequality-operator.spanish.md @@ -0,0 +1,82 @@ +--- +id: 56533eb9ac21ba0edf2244d3 +title: Comparison with the Strict Inequality Operator +localeTitle: Comparación con el operador de desigualdad estricta +challengeType: 1 +--- + +## Description +
+El operador de desigualdad estricta ( !== ) es el opuesto lógico del operador de igualdad estricta. Significa "Estrictamente no es igual" y devuelve false donde la igualdad estricta sería true y viceversa . La desigualdad estricta no convertirá los tipos de datos. +ejemplos +
3 !== 3 // false
3 !== '3' // true
4 !== 3 // true
+
+ +## Instructions +
+Agregue el strict inequality operator a la sentencia if para que la función devuelva "No igual" cuando val no sea estrictamente igual a 17 +
+ +## Tests +
+ +```yml +tests: + - text: testStrictNotEqual(17) debe devolver "Equal" + testString: 'assert(testStrictNotEqual(17) === "Equal", "testStrictNotEqual(17) should return "Equal"");' + - text: testStrictNotEqual("17") debe devolver "Not Equal" + testString: 'assert(testStrictNotEqual("17") === "Not Equal", "testStrictNotEqual("17") should return "Not Equal"");' + - text: testStrictNotEqual(12) debe devolver "Not Equal" + testString: 'assert(testStrictNotEqual(12) === "Not Equal", "testStrictNotEqual(12) should return "Not Equal"");' + - text: testStrictNotEqual("bob") debe devolver "Not Equal" + testString: 'assert(testStrictNotEqual("bob") === "Not Equal", "testStrictNotEqual("bob") should return "Not Equal"");' + - text: Debes usar el operador !== + testString: 'assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0, "You should use the !== operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function testStrictNotEqual(val) { + // Only Change Code Below this Line + + if (val) { + + // Only Change Code Above this Line + + return "Not Equal"; + } + return "Equal"; +} + +// Change this value to test +testStrictNotEqual(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testStrictNotEqual(val) { + if (val !== 17) { + return "Not Equal"; + } + return "Equal"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.spanish.md new file mode 100644 index 0000000000..72ff979ebd --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator.spanish.md @@ -0,0 +1,94 @@ +--- +id: 56533eb9ac21ba0edf2244d8 +title: Comparisons with the Logical And Operator +localeTitle: Comparaciones con lo lógico y el operador. +challengeType: 1 +--- + +## Description +
+A veces necesitará probar más de una cosa a la vez. La lógica y el operador ( && ) devuelven true si y solo si los operandos a su izquierda y derecha son verdaderos. +El mismo efecto podría lograrse anidando una instrucción if dentro de otra if: +
if (num > 5) {
  if (num < 10) {
    return "Yes";
  }
}
return "No";
+solo devolverá "Sí" si num es mayor que 5 y menor que 10 . La misma lógica se puede escribir como: +
if (num > 5 && num < 10) {
  return "Yes";
}
return "No";
+
+ +## Instructions +
+Combine las dos declaraciones if en una declaración que devolverá "Yes" si val es menor o igual a 50 y mayor o igual a 25 . De lo contrario, devolverá "No" . +
+ +## Tests +
+ +```yml +tests: + - text: Debe usar el operador && una vez + testString: 'assert(code.match(/&&/g).length === 1, "You should use the && operator once");' + - text: Sólo debe tener una declaración if + testString: 'assert(code.match(/if/g).length === 1, "You should only have one if statement");' + - text: testLogicalAnd(0) debe devolver "No" + testString: 'assert(testLogicalAnd(0) === "No", "testLogicalAnd(0) should return "No"");' + - text: testLogicalAnd(24) debe devolver "No" + testString: 'assert(testLogicalAnd(24) === "No", "testLogicalAnd(24) should return "No"");' + - text: testLogicalAnd(25) debe devolver "Sí" + testString: 'assert(testLogicalAnd(25) === "Yes", "testLogicalAnd(25) should return "Yes"");' + - text: testLogicalAnd(30) debe devolver "Sí" + testString: 'assert(testLogicalAnd(30) === "Yes", "testLogicalAnd(30) should return "Yes"");' + - text: testLogicalAnd(50) debe devolver "Sí" + testString: 'assert(testLogicalAnd(50) === "Yes", "testLogicalAnd(50) should return "Yes"");' + - text: testLogicalAnd(51) debe devolver "No" + testString: 'assert(testLogicalAnd(51) === "No", "testLogicalAnd(51) should return "No"");' + - text: testLogicalAnd(75) debe devolver "No" + testString: 'assert(testLogicalAnd(75) === "No", "testLogicalAnd(75) should return "No"");' + - text: testLogicalAnd(80) debe devolver "No" + testString: 'assert(testLogicalAnd(80) === "No", "testLogicalAnd(80) should return "No"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testLogicalAnd(val) { + // Only change code below this line + + if (val) { + if (val) { + return "Yes"; + } + } + + // Only change code above this line + return "No"; +} + +// Change this value to test +testLogicalAnd(10); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testLogicalAnd(val) { + if (val >= 25 && val <= 50) { + return "Yes"; + } + return "No"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.spanish.md new file mode 100644 index 0000000000..0fd8f4cc3f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-or-operator.spanish.md @@ -0,0 +1,97 @@ +--- +id: 56533eb9ac21ba0edf2244d9 +title: Comparisons with the Logical Or Operator +localeTitle: Comparaciones con el operador lógico o +challengeType: 1 +--- + +## Description +
+El lógico u operador ( || ) devuelve true si cualquiera de los operandos es true . De lo contrario, devuelve false . +El operador lógico está compuesto de dos símbolos de tubería ( | ). Normalmente, esto se puede encontrar entre las teclas Retroceso e Intro. +El patrón a continuación debe parecer familiar de los puntos de paso anteriores: +
if (num > 10) {
  return "No";
}
if (num < 5) {
  return "No";
}
return "Yes";
+devolverá "Sí" solo si el num está entre 5 y 10 (5 y 10 incluidos). La misma lógica se puede escribir como: +
if (num > 10 || num < 5) {
  return "No";
}
return "Yes";
+
+ +## Instructions +
+Combine las dos declaraciones if en una declaración que devuelva "Outside" si val no está entre 10 y 20 , inclusive. De lo contrario, devuelve "Inside" . +
+ +## Tests +
+ +```yml +tests: + - text: Deberías usar el || operador una vez + testString: 'assert(code.match(/\|\|/g).length === 1, "You should use the || operator once");' + - text: Sólo debe tener una declaración if + testString: 'assert(code.match(/if/g).length === 1, "You should only have one if statement");' + - text: testLogicalOr(0) debe devolver "Outside" + testString: 'assert(testLogicalOr(0) === "Outside", "testLogicalOr(0) should return "Outside"");' + - text: testLogicalOr(9) debe devolver "Outside" + testString: 'assert(testLogicalOr(9) === "Outside", "testLogicalOr(9) should return "Outside"");' + - text: testLogicalOr(10) debe devolver "Inside" + testString: 'assert(testLogicalOr(10) === "Inside", "testLogicalOr(10) should return "Inside"");' + - text: testLogicalOr(15) debe devolver "Inside" + testString: 'assert(testLogicalOr(15) === "Inside", "testLogicalOr(15) should return "Inside"");' + - text: testLogicalOr(19) debe devolver "Inside" + testString: 'assert(testLogicalOr(19) === "Inside", "testLogicalOr(19) should return "Inside"");' + - text: testLogicalOr(20) debe devolver "Inside" + testString: 'assert(testLogicalOr(20) === "Inside", "testLogicalOr(20) should return "Inside"");' + - text: testLogicalOr(21) debe devolver "Outside" + testString: 'assert(testLogicalOr(21) === "Outside", "testLogicalOr(21) should return "Outside"");' + - text: testLogicalOr(25) debe devolver "Outside" + testString: 'assert(testLogicalOr(25) === "Outside", "testLogicalOr(25) should return "Outside"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testLogicalOr(val) { + // Only change code below this line + + if (val) { + return "Outside"; + } + + if (val) { + return "Outside"; + } + + // Only change code above this line + return "Inside"; +} + +// Change this value to test +testLogicalOr(15); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testLogicalOr(val) { + if (val < 10 || val > 20) { + return "Outside"; + } + return "Inside"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.spanish.md new file mode 100644 index 0000000000..e499e3fbdf --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-addition.spanish.md @@ -0,0 +1,88 @@ +--- +id: 56533eb9ac21ba0edf2244af +title: Compound Assignment With Augmented Addition +localeTitle: Asignación compuesta con adición aumentada +challengeType: 1 +--- + +## Description +
+En la programación, es común usar asignaciones para modificar el contenido de una variable. Recuerde que todo a la derecha del signo igual se evalúa primero, por lo que podemos decir: +myVar = myVar + 5; +para agregar 5 a myVar . Dado que este es un patrón tan común, hay operadores que realizan tanto una operación matemática como una asignación en un solo paso. +Uno de tales operadores es el operador += . +
var myVar = 1;
myVar += 5;
console.log(myVar); // Returns 6
+
+ +## Instructions +
+Convierta las asignaciones para a , b y c para usar el operador += . +
+ +## Tests +
+ +```yml +tests: + - text: a debe ser igual a 15 + testString: 'assert(a === 15, "a should equal 15");' + - text: b debe ser igual a 26 + testString: 'assert(b === 26, "b should equal 26");' + - text: c debería ser igual a 19 + testString: 'assert(c === 19, "c should equal 19");' + - text: Debes usar el operador += para cada variable + testString: 'assert(code.match(/\+=/g).length === 3, "You should use the += operator for each variable");' + - text: No modifique el código sobre la línea. + testString: 'assert(/var a = 3;/.test(code) && /var b = 17;/.test(code) && /var c = 12;/.test(code), "Do not modify the code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var a = 3; +var b = 17; +var c = 12; + +// Only modify code below this line + +a = a + 12; +b = 9 + b; +c = c + 7; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 3; +var b = 17; +var c = 12; + +a += 12; +b += 9; +c += 7; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-division.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-division.spanish.md new file mode 100644 index 0000000000..5751941d21 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-division.spanish.md @@ -0,0 +1,87 @@ +--- +id: 56533eb9ac21ba0edf2244b2 +title: Compound Assignment With Augmented Division +localeTitle: Asignación compuesta con división aumentada +challengeType: 1 +--- + +## Description +
+El operador /= divide una variable por otro número. +myVar = myVar / 5; +myVar por 5 . Esto se puede reescribir como: +myVar /= 5; +
+ +## Instructions +
+Convierta las asignaciones para a , b y c para usar el operador /= . +
+ +## Tests +
+ +```yml +tests: + - text: a debería ser igual a 4 + testString: 'assert(a === 4, "a should equal 4");' + - text: b debería ser igual a 27 + testString: 'assert(b === 27, "b should equal 27");' + - text: c debería ser igual a 3 + testString: 'assert(c === 3, "c should equal 3");' + - text: Debes usar el operador /= para cada variable + testString: 'assert(code.match(/\/=/g).length === 3, "You should use the /= operator for each variable");' + - text: No modifique el código sobre la línea. + testString: 'assert(/var a = 48;/.test(code) && /var b = 108;/.test(code) && /var c = 33;/.test(code), "Do not modify the code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var a = 48; +var b = 108; +var c = 33; + +// Only modify code below this line + +a = a / 12; +b = b / 4; +c = c / 11; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 48; +var b = 108; +var c = 33; + +a /= 12; +b /= 4; +c /= 11; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-multiplication.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-multiplication.spanish.md new file mode 100644 index 0000000000..0c4ac859a9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-multiplication.spanish.md @@ -0,0 +1,88 @@ +--- +id: 56533eb9ac21ba0edf2244b1 +title: Compound Assignment With Augmented Multiplication +localeTitle: Asignación compuesta con multiplicación aumentada +challengeType: 1 +--- + +## Description +
+El operador *= multiplica una variable por un número. +myVar = myVar * 5; +multiplicará myVar por 5 . Esto se puede reescribir como: +myVar *= 5; +
+ +## Instructions +
+Convierta las asignaciones para a , b y c para usar el operador *= . +
+ +## Tests +
+ +```yml +tests: + - text: a debe ser igual a 25 + testString: 'assert(a === 25, "a should equal 25");' + - text: b debe ser igual a 36 + testString: 'assert(b === 36, "b should equal 36");' + - text: c debería ser igual a 46 + testString: 'assert(c === 46, "c should equal 46");' + - text: Debes usar el operador *= para cada variable + testString: 'assert(code.match(/\*=/g).length === 3, "You should use the *= operator for each variable");' + - text: No modifique el código sobre la línea. + testString: 'assert(/var a = 5;/.test(code) && /var b = 12;/.test(code) && /var c = 4\.6;/.test(code), "Do not modify the code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var a = 5; +var b = 12; +var c = 4.6; + +// Only modify code below this line + +a = a * 5; +b = 3 * b; +c = c * 10; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 5; +var b = 12; +var c = 4.6; + +a *= 5; +b *= 3; +c *= 10; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-subtraction.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-subtraction.spanish.md new file mode 100644 index 0000000000..f5aad7e776 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/compound-assignment-with-augmented-subtraction.spanish.md @@ -0,0 +1,90 @@ +--- +id: 56533eb9ac21ba0edf2244b0 +title: Compound Assignment With Augmented Subtraction +localeTitle: Asignación compuesta con resta aumentada +challengeType: 1 +--- + +## Description +
+Al igual que el operador += , -= resta un número de una variable. +myVar = myVar - 5; +restará 5 de myVar . Esto se puede reescribir como: +myVar -= 5; +
+ +## Instructions +
+Convierta las asignaciones para a , b y c para usar el operador -= . +
+ +## Tests +
+ +```yml +tests: + - text: a debe ser igual a 5 + testString: 'assert(a === 5, "a should equal 5");' + - text: b debería ser igual a -6 + testString: 'assert(b === -6, "b should equal -6");' + - text: c debería ser igual a 2 + testString: 'assert(c === 2, "c should equal 2");' + - text: Debe usar el operador -= para cada variable + testString: 'assert(code.match(/-=/g).length === 3, "You should use the -= operator for each variable");' + - text: No modifique el código sobre la línea. + testString: 'assert(/var a = 11;/.test(code) && /var b = 9;/.test(code) && /var c = 3;/.test(code), "Do not modify the code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var a = 11; +var b = 9; +var c = 3; + +// Only modify code below this line + +a = a - 6; +b = b - 15; +c = c - 1; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 11; +var b = 9; +var c = 3; + +a -= 6; +b -= 15; +c -= 1; + + +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.spanish.md new file mode 100644 index 0000000000..d911c5d64b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-plus-operator.spanish.md @@ -0,0 +1,78 @@ +--- +id: 56533eb9ac21ba0edf2244b7 +title: Concatenating Strings with Plus Operator +localeTitle: Concatenando cuerdas con el operador Plus +challengeType: 1 +--- + +## Description +
+En JavaScript, cuando el operador + se usa con un valor de String , se llama operador de concatenación . Puede construir una nueva cadena a partir de otras cadenas concatenándolas juntas. +Ejemplo +
'My name is Alan,' + ' I concatenate.'
+Nota
Cuidado con los espacios. La concatenación no agrega espacios entre las cadenas concatenadas, por lo que deberá agregarlas usted mismo. +
+ +## Instructions +
+Construye myStr partir de las cadenas "This is the start. " y "This is the end." utilizando el operador + . +
+ +## Tests +
+ +```yml +tests: + - text: myStr debe tener un valor de This is the start. This is the end. + testString: 'assert(myStr === "This is the start. This is the end.", "myStr should have a value of This is the start. This is the end.");' + - text: Usa el operador + para construir myStr + testString: 'assert(code.match(/([""]).*([""])\s*\+\s*([""]).*([""])/g).length > 1, "Use the + operator to build myStr");' + - text: myStr debe crearse usando la palabra clave var . + testString: 'assert(/var\s+myStr/.test(code), "myStr should be created using the var keyword.");' + - text: Asegúrese de asignar el resultado a la variable myStr . + testString: 'assert(/myStr\s*=/.test(code), "Make sure to assign the result to the myStr variable.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourStr = "I come first. " + "I come second."; + +// Only change code below this line + +var myStr; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourStr = "I come first. " + "I come second."; +var myStr = "This is the start. " + "This is the end."; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.spanish.md new file mode 100644 index 0000000000..6f4db4cea4 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/concatenating-strings-with-the-plus-equals-operator.spanish.md @@ -0,0 +1,76 @@ +--- +id: 56533eb9ac21ba0edf2244b8 +title: Concatenating Strings with the Plus Equals Operator +localeTitle: Concatenando cadenas con el operador Plus Equals +challengeType: 1 +--- + +## Description +
+También podemos usar el operador += para concatenar una cadena al final de una variable de cadena existente. Esto puede ser muy útil para romper una cadena larga en varias líneas. +Nota
Cuidado con los espacios. La concatenación no agrega espacios entre las cadenas concatenadas, por lo que deberá agregarlas usted mismo. +
+ +## Instructions +
+Construya myStr en varias líneas concatenando estas dos cadenas: "This is the first sentence. " y "This is the second sentence." utilizando el operador += . Utilice el operador += similar a como se muestra en el editor. Comience por asignar la primera cadena a myStr , luego agregue la segunda cadena. +
+ +## Tests +
+ +```yml +tests: + - text: myStr debe tener un valor de This is the first sentence. This is the second sentence. + testString: 'assert(myStr === "This is the first sentence. This is the second sentence.", "myStr should have a value of This is the first sentence. This is the second sentence.");' + - text: Usa el operador += para construir myStr + testString: 'assert(code.match(/\w\s*\+=\s*[""]/g).length > 1 && code.match(/\w\s*\=\s*[""]/g).length > 1, "Use the += operator to build myStr");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourStr = "I come first. "; +ourStr += "I come second."; + +// Only change code below this line + +var myStr; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourStr = "I come first. "; +ourStr += "I come second."; + +var myStr = "This is the first sentence. "; +myStr += "This is the second sentence."; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.spanish.md new file mode 100644 index 0000000000..b16bcac0db --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/constructing-strings-with-variables.spanish.md @@ -0,0 +1,72 @@ +--- +id: 56533eb9ac21ba0edf2244b9 +title: Constructing Strings with Variables +localeTitle: Construyendo cuerdas con variables +challengeType: 1 +--- + +## Description +
+A veces necesitarás construir una cadena, al estilo de Mad Libs . Al utilizar el operador de concatenación ( + ), puede insertar una o más variables en una cadena que está creando. +
+ +## Instructions +
+Establezca myName en una cadena igual a su nombre y compile myStr con myName entre las cadenas "My name is " y " and I am well!" +
+ +## Tests +
+ +```yml +tests: + - text: myName debe establecerse en una cadena de al menos 3 caracteres + testString: 'assert(typeof myName !== "undefined" && myName.length > 2, "myName should be set to a string at least 3 characters long");' + - text: Usa dos operadores + para construir myStr con myName dentro de él + testString: 'assert(code.match(/[""]\s*\+\s*myName\s*\+\s*[""]/g).length > 0, "Use two + operators to build myStr with myName inside it");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourName = "freeCodeCamp"; +var ourStr = "Hello, our name is " + ourName + ", how are you?"; + +// Only change code below this line +var myName; +var myStr; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myName = "Bob"; +var myStr = "My name is " + myName + " and I am well!"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.spanish.md new file mode 100644 index 0000000000..5be351d155 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/count-backwards-with-a-for-loop.spanish.md @@ -0,0 +1,89 @@ +--- +id: 56105e7b514f539506016a5e +title: Count Backwards With a For Loop +localeTitle: Contar hacia atrás con un bucle for +challengeType: 1 +--- + +## Description +
+A for loop también puede contar hacia atrás, siempre que podamos definir las condiciones correctas. +Para contar hacia atrás de dos en dos, necesitaremos cambiar nuestra initialization , condition y final-expression . +Comenzaremos en i = 10 y haremos un bucle mientras i > 0 . Disminuiremos i en 2 cada bucle con i -= 2 . +
var ourArray = [];
for (var i=10; i > 0; i-=2) {
  ourArray.push(i);
}
+ourArray ahora contendrá [10,8,6,4,2] . +Cambiemos nuestra initialization y final-expression para que podamos contar hacia atrás de dos en dos con números impares. +
+ +## Instructions +
+Empuje los números impares del 9 al 1 a myArray usando un bucle for . +
+ +## Tests +
+ +```yml +tests: + - text: Usted debe estar usando una for bucle para esto. + testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a for loop for this.");' + - text: Deberías estar usando el método de matriz push . + testString: 'assert(code.match(/myArray.push/), "You should be using the array method push.");' + - text: ' myArray debe ser igual a [9,7,5,3,1] .' + testString: 'assert.deepEqual(myArray, [9,7,5,3,1], "myArray should equal [9,7,5,3,1].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = []; + +for (var i = 10; i > 0; i -= 2) { + ourArray.push(i); +} + +// Setup +var myArray = []; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourArray = []; +for (var i = 10; i > 0; i -= 2) { + ourArray.push(i); +} +var myArray = []; +for (var i = 9; i > 0; i -= 2) { + myArray.push(i); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.spanish.md new file mode 100644 index 0000000000..2e9185a22b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/counting-cards.spanish.md @@ -0,0 +1,104 @@ +--- +id: 565bbe00e9cc8ac0725390f4 +title: Counting Cards +localeTitle: Tarjetas de conteo +challengeType: 1 +--- + +## Description +
+En el juego de casino Blackjack, un jugador puede obtener una ventaja sobre la casa al hacer un seguimiento del número relativo de cartas altas y bajas que quedan en el mazo. Esto se llama conteo de cartas . +Tener más cartas altas en el mazo favorece al jugador. A cada tarjeta se le asigna un valor de acuerdo con la siguiente tabla. Cuando el conteo es positivo, el jugador debe apostar alto. Cuando el conteo es cero o negativo, el jugador debe apostar bajo. +
Cambio de cuenta Tarjetas
+1 2, 3, 4, 5, 6
0 7, 8, 9
-1 10, 'J', 'Q', 'K', 'A'
+Escribirás una función de conteo de cartas. Recibirá un parámetro de card , que puede ser un número o una cadena, y aumentará o disminuirá la variable de count global según el valor de la tarjeta (consulte la tabla). La función devolverá una cadena con el recuento actual y la cadena Bet si el recuento es positivo, o Hold si el recuento es cero o negativo. El conteo actual y la decisión del jugador ( Bet o Hold ) deben estar separados por un solo espacio. +Ejemplo de salida
-3 Hold
5 Bet +Sugerencia
NO reinicie el count a 0 cuando el valor sea 7, 8 o 9.
NO devuelva una matriz.
NO incluya comillas (simples o dobles) en la salida. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: 'Las secuencias de cartas 2, 3, 4, 5, 6 deben devolver 5 Bet ' + testString: 'assert((function(){ count = 0; cc(2);cc(3);cc(4);cc(5);var out = cc(6); if(out === "5 Bet") {return true;} return false; })(), "Cards Sequence 2, 3, 4, 5, 6 should return 5 Bet");' + - text: 'Las secuencias de cartas 7, 8, 9 deben devolver 0 Hold ' + testString: 'assert((function(){ count = 0; cc(7);cc(8);var out = cc(9); if(out === "0 Hold") {return true;} return false; })(), "Cards Sequence 7, 8, 9 should return 0 Hold");' + - text: 'La secuencia de cartas 10, J, Q, K, A debería devolver -5 Hold ' + testString: 'assert((function(){ count = 0; cc(10);cc("J");cc("Q");cc("K");var out = cc("A"); if(out === "-5 Hold") {return true;} return false; })(), "Cards Sequence 10, J, Q, K, A should return -5 Hold");' + - text: 'Las secuencias de cartas 3, 7, Q, 8, A deben devolver -1 Hold ' + testString: 'assert((function(){ count = 0; cc(3);cc(7);cc("Q");cc(8);var out = cc("A"); if(out === "-1 Hold") {return true;} return false; })(), "Cards Sequence 3, 7, Q, 8, A should return -1 Hold");' + - text: 'Las secuencias de cartas 2, J, 9, 2, 7 deben devolver 1 Bet ' + testString: 'assert((function(){ count = 0; cc(2);cc("J");cc(9);cc(2);var out = cc(7); if(out === "1 Bet") {return true;} return false; })(), "Cards Sequence 2, J, 9, 2, 7 should return 1 Bet");' + - text: 'Las secuencias de cartas 2, 2, 10 deben devolver 1 Bet ' + testString: 'assert((function(){ count = 0; cc(2);cc(2);var out = cc(10); if(out === "1 Bet") {return true;} return false; })(), "Cards Sequence 2, 2, 10 should return 1 Bet");' + - text: 'Secuencia de cartas 3, 2, A, 10, K debería devolver -1 Hold ' + testString: 'assert((function(){ count = 0; cc(3);cc(2);cc("A");cc(10);var out = cc("K"); if(out === "-1 Hold") {return true;} return false; })(), "Cards Sequence 3, 2, A, 10, K should return -1 Hold");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var count = 0; + +function cc(card) { + // Only change code below this line + + + return "Change Me"; + // Only change code above this line +} + +// Add/remove calls to test your function. +// Note: Only the last will display +cc(2); cc(3); cc(7); cc('K'); cc('A'); +``` + +
+ + + +
+ +## Solution +
+ + +```js +var count = 0; +function cc(card) { + switch(card) { + case 2: + case 3: + case 4: + case 5: + case 6: + count++; + break; + case 10: + case 'J': + case 'Q': + case 'K': + case 'A': + count--; + } + if(count > 0) { + return count + " Bet"; + } else { + return count + " Hold"; + } +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.spanish.md new file mode 100644 index 0000000000..9953963ed7 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/create-decimal-numbers-with-javascript.spanish.md @@ -0,0 +1,68 @@ +--- +id: cf1391c1c11feddfaeb4bdef +title: Create Decimal Numbers with JavaScript +localeTitle: Crea números decimales con JavaScript +challengeType: 1 +--- + +## Description +
+Podemos almacenar números decimales en variables también. Los números decimales a veces se denominan números de punto flotante o flotantes . +Nota
No todos los números reales se pueden representar con precisión en coma flotante . Esto puede llevar a errores de redondeo. Detalles aquí . +
+ +## Instructions +
+Crea una variable myDecimal y dale un valor decimal con una parte fraccionaria (por ejemplo, 5.7 ). +
+ +## Tests +
+ +```yml +tests: + - text: myDecimal debe ser un número. + testString: 'assert(typeof myDecimal === "number", "myDecimal should be a number.");' + - text: myDecimal debería tener un punto decimal + testString: 'assert(myDecimal % 1 != 0, "myDecimal should have a decimal point"); ' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var ourDecimal = 5.7; + +// Only change code below this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myDecimal = 9.9; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.spanish.md new file mode 100644 index 0000000000..36c6bcba77 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-javascript-variables.spanish.md @@ -0,0 +1,73 @@ +--- +id: bd7123c9c443eddfaeb5bdef +title: Declare JavaScript Variables +localeTitle: Declarar las variables de JavaScript +challengeType: 1 +--- + +## Description +
+En informática, los datos son cualquier cosa que sea significativa para la computadora. JavaScript proporciona siete tipos de datos diferentes que son undefined , null , boolean , string , symbol , number y object . +Por ejemplo, las computadoras distinguen entre los números, como el número 12 , y las strings , como "12" , "dog" o "123 cats" , que son colecciones de caracteres. Las computadoras pueden realizar operaciones matemáticas en un número, pero no en una cadena. +Las variables permiten que las computadoras almacenen y manipulen datos de una manera dinámica. Hacen esto usando una "etiqueta" para señalar los datos en lugar de usar los datos en sí. Cualquiera de los siete tipos de datos puede almacenarse en una variable. +Variables son similares a las variables x e y que usa en matemáticas, lo que significa que son un nombre simple para representar los datos a los que queremos referirnos. Las variables computadora difieren de las variables matemáticas en que pueden almacenar diferentes valores en diferentes momentos. +Le pedimos a JavaScript que cree o declare una variable poniendo la palabra clave var delante de ella, así: +
var ourName;
+crea una variable llamada ourName . En JavaScript terminamos las frases con punto y coma. +Variable nombres de las Variable pueden estar formados por números, letras y $ o _ , pero no pueden contener espacios ni comenzar con un número. +
+ +## Instructions +
+Use la palabra clave var para crear una variable llamada myName . +Pista
Mira el ejemplo de ourName si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: 'Debes declarar myName con la palabra clave var , que termina con un punto y coma' + testString: 'assert(/var\s+myName\s*;/.test(code), "You should declare myName with the var keyword, ending with a semicolon");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourName; + +// Declare myName below this line + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myName; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.spanish.md new file mode 100644 index 0000000000..c7a518f364 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/declare-string-variables.spanish.md @@ -0,0 +1,72 @@ +--- +id: bd7123c9c444eddfaeb5bdef +title: Declare String Variables +localeTitle: Declarar variables de cadena +challengeType: 1 +--- + +## Description +
+Anteriormente hemos utilizado el código +var myName = "your name"; +"your name" se llama una cadena literal . Es una cadena porque es una serie de cero o más caracteres entre comillas simples o dobles. +
+ +## Instructions +
+Crea dos nuevas variables de string : myFirstName y myLastName y asigna los valores de tu nombre y apellido, respectivamente. +
+ +## Tests +
+ +```yml +tests: + - text: myFirstName debe ser una cadena con al menos un carácter. + testString: 'assert((function(){if(typeof myFirstName !== "undefined" && typeof myFirstName === "string" && myFirstName.length > 0){return true;}else{return false;}})(), "myFirstName should be a string with at least one character in it.");' + - text: myLastName debe ser una cadena con al menos un carácter. + testString: 'assert((function(){if(typeof myLastName !== "undefined" && typeof myLastName === "string" && myLastName.length > 0){return true;}else{return false;}})(), "myLastName should be a string with at least one character in it.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstName = "Alan"; +var lastName = "Turing"; + +// Only change code below this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myFirstName = "Alan"; +var myLastName = "Turing"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.spanish.md new file mode 100644 index 0000000000..63a952199a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/decrement-a-number-with-javascript.spanish.md @@ -0,0 +1,76 @@ +--- +id: 56533eb9ac21ba0edf2244ad +title: Decrement a Number with JavaScript +localeTitle: Disminuir un número con JavaScript +challengeType: 1 +--- + +## Description +
+Puede disminuir o disminuir fácilmente una variable por una con el operador -- . +i--; +es el equivalente de +i = i - 1; +Nota
La línea entera se convierte en i--; , eliminando la necesidad del signo igual. +
+ +## Instructions +
+Cambie el código para usar el operador -- en myVar . +
+ +## Tests +
+ +```yml +tests: + - text: myVar debe ser igual a 10 + testString: 'assert(myVar === 10, "myVar should equal 10");' + - text: myVar = myVar - 1; debería ser cambiado + testString: 'assert(/var\s*myVar\s*=\s*11;\s*\/*.*\s*([-]{2}\s*myVar|myVar\s*[-]{2});/.test(code), "myVar = myVar - 1; should be changed");' + - text: Utilice el -- operador en myVar + testString: 'assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code), "Use the -- operator on myVar");' + - text: No cambie el código por encima de la línea + testString: 'assert(/var myVar = 11;/.test(code), "Do not change code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myVar = 11; + +// Only change code below this line +myVar = myVar - 1; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myVar = 11; +myVar--; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.spanish.md new file mode 100644 index 0000000000..03f181d512 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/delete-properties-from-a-javascript-object.spanish.md @@ -0,0 +1,100 @@ +--- +id: 56bbb991ad1ed5201cd392d3 +title: Delete Properties from a JavaScript Object +localeTitle: Eliminar propiedades de un objeto de JavaScript +challengeType: 1 +--- + +## Description +
+También podemos eliminar propiedades de objetos como este: +delete ourDog.bark; +
+ +## Instructions +
+Eliminar la propiedad "tails" de myDog . Puede usar la notación de punto o corchete. +
+ +## Tests +
+ +```yml +tests: + - text: Eliminar la propiedad "tails" de myDog . + testString: 'assert(typeof myDog === "object" && myDog.tails === undefined, "Delete the property "tails" from myDog.");' + - text: No modifique la configuración de myDog + testString: 'assert(code.match(/"tails": 1/g).length > 1, "Do not modify the myDog setup");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"], + "bark": "bow-wow" +}; + +delete ourDog.bark; + +// Setup +var myDog = { + "name": "Happy Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"], + "bark": "woof" +}; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"], + "bark": "bow-wow" +}; +var myDog = { + "name": "Happy Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"], + "bark": "woof" +}; +delete myDog.tails; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-decimal-by-another-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-decimal-by-another-with-javascript.spanish.md new file mode 100644 index 0000000000..d9020cdbc2 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-decimal-by-another-with-javascript.spanish.md @@ -0,0 +1,65 @@ +--- +id: bd7993c9ca9feddfaeb7bdef +title: Divide One Decimal by Another with JavaScript +localeTitle: Divide un decimal por otro con JavaScript +challengeType: 1 +--- + +## Description +
+Ahora dividamos un decimal por otro. +
+ +## Instructions +
+Cambie el 0.0 para que el quotient sea ​​igual a 2.2 . +
+ +## Tests +
+ +```yml +tests: + - text: El quotient variable debe ser igual a 2.2 + testString: 'assert(quotient === 2.2, "The variable quotient should equal 2.2");' + - text: Debes usar el operador / para dividir 4.4 por 2 + testString: 'assert(/4\.40*\s*\/\s*2\.*0*/.test(code), "You should use the / operator to divide 4.4 by 2");' + - text: La variable de cociente solo debe ser asignada una vez. + testString: 'assert(code.match(/quotient/g).length === 1, "The quotient variable should only be assigned once");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var quotient = 0.0 / 2.0; // Fix this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.spanish.md new file mode 100644 index 0000000000..04980f7394 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/divide-one-number-by-another-with-javascript.spanish.md @@ -0,0 +1,70 @@ +--- +id: cf1111c1c11feddfaeb6bdef +title: Divide One Number by Another with JavaScript +localeTitle: Divide un número por otro con JavaScript +challengeType: 1 +--- + +## Description +
+También podemos dividir un número por otro. +JavaScript usa el símbolo / para la división. + +Ejemplo +
myVar = 16 / 2; // assigned 8
+ +
+ +## Instructions +
+Cambia el 0 para que el quotient sea ​​igual a 2 . +
+ +## Tests +
+ +```yml +tests: + - text: Haz que el quotient variable sea igual a 2. + testString: 'assert(quotient === 2, "Make the variable quotient equal to 2.");' + - text: Usa el operador / + testString: 'assert(/\d+\s*\/\s*\d+/.test(code), "Use the / operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var quotient = 66 / 0; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var quotient = 66 / 33; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.spanish.md new file mode 100644 index 0000000000..244cd17937 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escape-sequences-in-strings.spanish.md @@ -0,0 +1,79 @@ +--- +id: 56533eb9ac21ba0edf2244b6 +title: Escape Sequences in Strings +localeTitle: Secuencias de escape en cuerdas +challengeType: 1 +--- + +## Description +
+comillas no son los únicos caracteres que pueden escaparse dentro de una cadena. Hay dos razones para usar caracteres que se escapan: primero es permitirle usar caracteres que de otra forma no podría escribir, como un retroceso. El segundo es permitirte representar múltiples citas en una cadena sin que JavaScript interprete mal lo que quieres decir. Aprendimos esto en el reto anterior. +
Código Salida
\' una frase
\" doble cita
\\ barra invertida
\n nueva línea
\r retorno de carro
\t lengüeta
\b retroceso
\f form feed
+Tenga en cuenta que la barra invertida debe escaparse para que se muestre como una barra invertida. +
+ +## Instructions +
+Asigne las siguientes tres líneas de texto a la única variable myStr usando secuencias de escape. +
FirstLine
    \SecondLine
ThirdLine
+Necesitará usar secuencias de escape para insertar caracteres especiales correctamente. También deberá seguir el espaciado como se ve arriba, sin espacios entre las secuencias de escape o las palabras. +Aquí está el texto con las secuencias de escape escritas. +FirstLine newline tab backslash SecondLine newline ThirdLine +
+ +## Tests +
+ +```yml +tests: + - text: myStr no debe contener espacios + testString: 'assert(!/ /.test(myStr), "myStr should not contain any spaces");' + - text: ' myStr debe contener las cadenas FirstLine , SecondLine y ThirdLine (recuerda la sensibilidad a los casos)' + testString: 'assert(/FirstLine/.test(myStr) && /SecondLine/.test(myStr) && /ThirdLine/.test(myStr), "myStr should contain the strings FirstLine, SecondLine and ThirdLine (remember case sensitivity)");' + - text: FirstLine debe ir seguido del carácter de nueva línea \n + testString: 'assert(/FirstLine\n/.test(myStr), "FirstLine should be followed by the newline character \n");' + - text: myStr debe contener un carácter de tabulación \t que sigue a un carácter de nueva línea + testString: 'assert(/\n\t/.test(myStr), "myStr should contain a tab character \t which follows a newline character");' + - text: SecondLine debe ir precedida por el carácter de barra invertida \\ + testString: 'assert(/\SecondLine/.test(myStr), "SecondLine should be preceded by the backslash character \\");' + - text: Debe haber un carácter de nueva línea entre SecondLine y ThirdLine + testString: 'assert(/SecondLine\nThirdLine/.test(myStr), "There should be a newline character between SecondLine and ThirdLine");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myStr; // Change this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myStr = "FirstLine\n\t\\SecondLine\nThirdLine"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.spanish.md new file mode 100644 index 0000000000..e2c95396cb --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/escaping-literal-quotes-in-strings.spanish.md @@ -0,0 +1,70 @@ +--- +id: 56533eb9ac21ba0edf2244b5 +title: Escaping Literal Quotes in Strings +localeTitle: Escapar de citas literales en cuerdas +challengeType: 1 +--- + +## Description +
+Cuando está definiendo una cadena, debe comenzar y terminar con una comilla simple o doble. ¿Qué sucede cuando necesita una cita literal: " o ' dentro de su cadena? +En JavaScript, puede evitar que una cita la considere como un final de cadena de la cadena colocando una barra invertida ( \ ) delante de la cita. +var sampleStr = "Alan said, \"Peter is learning JavaScript\"."; +Esto indica a JavaScript que la siguiente cita no es el final de la cadena, sino que debería aparecer dentro de la cadena. Por lo tanto, si imprimiera esto en En la consola, obtendrías: +Alan said, "Peter is learning JavaScript". +
+ +## Instructions +
+Use barras diagonales inversas para asignar una cadena a la variable myStr modo que si tuviera que imprimirla en la consola, verá: +I am a "double quoted" string inside "double quotes". +
+ +## Tests +
+ +```yml +tests: + - text: 'Debería usar dos comillas dobles ( " ) y cuatro comillas dobles escapadas ( \" ).' + testString: 'assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2, "You should use two double quotes (") and four escaped double quotes (\").");' + - text: 'Variable myStr debe contener la cadena: I am a "double quoted" string inside "double quotes". comilla I am a "double quoted" string inside "double quotes". ' + testString: 'assert(myStr === "I am a \"double quoted\" string inside \"double quotes\".", "Variable myStr should contain the string: I am a "double quoted" string inside "double quotes".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myStr = ""; // Change this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myStr = "I am a \"double quoted\" string inside \"double quotes\"."; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.spanish.md new file mode 100644 index 0000000000..27ce7c2080 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/find-the-length-of-a-string.spanish.md @@ -0,0 +1,85 @@ +--- +id: bd7123c9c448eddfaeb5bdef +title: Find the Length of a String +localeTitle: Encuentra la longitud de una cuerda +challengeType: 1 +--- + +## Description +
+Puede encontrar la longitud de un valor de String escribiendo .length después de la variable de cadena o el literal de cadena. +"Alan Peter".length; // 10 +Por ejemplo, si creamos una variable var firstName = "Charles" , podríamos averiguar cuánto tiempo dura la cadena "Charles" utilizando la propiedad firstName.length . +
+ +## Instructions +
+Use la propiedad .length para contar el número de caracteres en la variable lastName y asignarla a lastNameLength . +
+ +## Tests +
+ +```yml +tests: + - text: lastNameLength debe ser igual a ocho. + testString: 'assert((function(){if(typeof lastNameLength !== "undefined" && typeof lastNameLength === "number" && lastNameLength === 8){return true;}else{return false;}})(), "lastNameLength should be equal to eight.");' + - text: 'Deberías obtener la longitud del lastName al usar .length esta manera: lastName.length '. + testString: 'assert((function(){if(code.match(/\.length/gi) && code.match(/\.length/gi).length >= 2 && code.match(/var lastNameLength \= 0;/gi) && code.match(/var lastNameLength \= 0;/gi).length >= 1){return true;}else{return false;}})(), "You should be getting the length of lastName by using .length like this: lastName.length.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstNameLength = 0; +var firstName = "Ada"; + +firstNameLength = firstName.length; + +// Setup +var lastNameLength = 0; +var lastName = "Lovelace"; + +// Only change code below this line. + +lastNameLength = lastName; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var firstNameLength = 0; +var firstName = "Ada"; +firstNameLength = firstName.length; + +var lastNameLength = 0; +var lastName = "Lovelace"; +lastNameLength = lastName.length; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.spanish.md new file mode 100644 index 0000000000..8c849fa33f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/finding-a-remainder-in-javascript.spanish.md @@ -0,0 +1,73 @@ +--- +id: 56533eb9ac21ba0edf2244ae +title: Finding a Remainder in JavaScript +localeTitle: Encontrar un resto en JavaScript +challengeType: 1 +--- + +## Description +
+El operador restante % da el resto de la división de dos números. +Ejemplo +
5 % 2 = 1 because
Math.floor(5 / 2) = 2 (Quotient)
2 * 2 = 4
5 - 4 = 1 (Remainder)
+Usage
En matemáticas, se puede verificar que un número sea par o impar verificando el resto de la división del número entre 2 . +
17 % 2 = 1 (17 is Odd)
48 % 2 = 0 (48 is Even)
+Nota
El operador del resto a veces se denomina incorrectamente operador del "módulo". Es muy similar al módulo, pero no funciona correctamente con números negativos. +
+ +## Instructions +
+Establezca el remainder igual al resto de 11 dividido por 3 usando el operador resto ( % ). +
+ +## Tests +
+ +```yml +tests: + - text: La variable remainder debe ser inicializada. + testString: 'assert(/var\s+?remainder/.test(code), "The variable remainder should be initialized");' + - text: El valor del remainder debe ser 2 + testString: 'assert(remainder === 2, "The value of remainder should be 2");' + - text: Debes usar el operador % + testString: 'assert(/\s+?remainder\s*?=\s*?.*%.*;/.test(code), "You should use the % operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Only change code below this line + +var remainder; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var remainder = 11 % 3; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.spanish.md new file mode 100644 index 0000000000..b7c6ffa229 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.spanish.md @@ -0,0 +1,76 @@ +--- +id: cf1111c1c11feddfaeb9bdef +title: Generate Random Fractions with JavaScript +localeTitle: Generar fracciones aleatorias con JavaScript +challengeType: 1 +--- + +## Description +
+Los números aleatorios son útiles para crear un comportamiento aleatorio. +JavaScript tiene una función Math.random() que genera un número decimal aleatorio entre 0 (incluido) y no hasta 1 (exclusivo). Por Math.random() tanto, Math.random() puede devolver un 0 pero nunca devolver completamente una Nota de 1 +
Al igual que el almacenamiento de valores con el operador igual , todas las llamadas de función se resolverán antes de que se ejecute la return , por lo que podemos return el valor de la función Math.random() . +
+ +## Instructions +
+Cambie randomFraction para devolver un número aleatorio en lugar de devolver 0 . +
+ +## Tests +
+ +```yml +tests: + - text: randomFraction debería devolver un número aleatorio. + testString: 'assert(typeof randomFraction() === "number", "randomFraction should return a random number.");' + - text: El número devuelto por randomFraction debe ser un decimal. + testString: 'assert((randomFraction()+""). match(/\./g), "The number returned by randomFraction should be a decimal.");' + - text: Debería estar usando Math.random para generar el número decimal aleatorio. + testString: 'assert(code.match(/Math\.random/g).length >= 0, "You should be using Math.random to generate the random decimal number.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function randomFraction() { + + // Only change code below this line. + + return 0; + + // Only change code above this line. +} +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function randomFraction() { + return Math.random(); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript.spanish.md new file mode 100644 index 0000000000..5a032b9064 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript.spanish.md @@ -0,0 +1,82 @@ +--- +id: cf1111c1c12feddfaeb1bdef +title: Generate Random Whole Numbers with JavaScript +localeTitle: Generar números enteros al azar con JavaScript +challengeType: 1 +--- + +## Description +
+Es genial que podamos generar números decimales aleatorios, pero es aún más útil si lo usamos para generar números enteros aleatorios. +
  1. Usa Math.random() para generar un decimal aleatorio.
  2. Multiplica ese decimal aleatorio por 20 .
  3. Use otra función, Math.floor() para redondear el número a su número entero más cercano.
+Recuerda que Math.random() nunca puede devolver un 1 y, porque estamos redondeando, es imposible obtener 20 . Esta técnica nos dará un número entero entre 0 y 19 . +Poniendo todo junto, así es como se ve nuestro código: +Math.floor(Math.random() * 20); +Estamos llamando a Math.random() , multiplicamos el resultado por 20 y luego Math.floor() el valor a la función Math.floor() para redondear el valor al número entero más cercano. +
+ +## Instructions +
+Use esta técnica para generar y devolver un número entero aleatorio entre 0 y 9 . +
+ +## Tests +
+ +```yml +tests: + - text: El resultado de randomWholeNum debe ser un número entero. + testString: 'assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), "The result of randomWholeNum should be a whole number.");' + - text: Debería estar usando Math.random para generar un número aleatorio. + testString: 'assert(code.match(/Math.random/g).length > 1, "You should be using Math.random to generate a random number.");' + - text: Debería haber multiplicado el resultado de Math.random por 10 para que sea un número entre cero y nueve. + testString: 'assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g), "You should have multiplied the result of Math.random by 10 to make it a number that is between zero and nine.");' + - text: Debe usar Math.floor para eliminar la parte decimal del número. + testString: 'assert(code.match(/Math.floor/g).length > 1, "You should use Math.floor to remove the decimal part of the number.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var randomNumberBetween0and19 = Math.floor(Math.random() * 20); + +function randomWholeNum() { + + // Only change code below this line. + + return Math.random(); +} +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var randomNumberBetween0and19 = Math.floor(Math.random() * 20); +function randomWholeNum() { + return Math.floor(Math.random() * 10); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range.spanish.md new file mode 100644 index 0000000000..feb1e64968 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range.spanish.md @@ -0,0 +1,89 @@ +--- +id: cf1111c1c12feddfaeb2bdef +title: Generate Random Whole Numbers within a Range +localeTitle: Generar números enteros al azar dentro de un rango +challengeType: 1 +--- + +## Description +
+En lugar de generar un número aleatorio entre cero y un número dado como hicimos antes, podemos generar un número aleatorio que se encuentre dentro de un rango de dos números específicos. +Para hacer esto, definiremos un número mínimo min y un máximo número max . +Aquí está la fórmula que usaremos. Tómese un momento para leerlo e intente entender lo que hace este código: +Math.floor(Math.random() * (max - min + 1)) + min +
+ +## Instructions +
+Cree una función llamada randomRange que tome un rango myMin y myMax y devuelva un número aleatorio que sea mayor o igual que myMin , y que sea menor o igual que myMax , inclusive. +
+ +## Tests +
+ +```yml +tests: + - text: 'El número aleatorio más bajo que puede ser generado por randomRange debería ser igual a tu número mínimo, myMin '. + testString: 'assert(calcMin === 5, "The lowest random number that can be generated by randomRange should be equal to your minimum number, myMin.");' + - text: "El número aleatorio más alto que puede ser generado por randomRange debería ser igual a tu número máximo, myMax ". + testString: 'assert(calcMax === 15, "The highest random number that can be generated by randomRange should be equal to your maximum number, myMax.");' + - text: 'El número aleatorio generado por randomRange debe ser un número entero, no un decimal'. + testString: 'assert(randomRange(0,1) % 1 === 0 , "The random number generated by randomRange should be an integer, not a decimal.");' + - text: ' randomRange debe usar myMax y myMin , y devolver un número aleatorio en tu rango'. + testString: 'assert((function(){if(code.match(/myMax/g).length > 1 && code.match(/myMin/g).length > 2 && code.match(/Math.floor/g) && code.match(/Math.random/g)){return true;}else{return false;}})(), "randomRange should use both myMax and myMin, and return a random number in your range.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +function ourRandomRange(ourMin, ourMax) { + + return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin; +} + +ourRandomRange(1, 9); + +// Only change code below this line. + +function randomRange(myMin, myMax) { + + return 0; // Change this line + +} + +// Change these values to test your function +var myRandom = randomRange(5, 15); +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function randomRange(myMin, myMax) { + return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.spanish.md new file mode 100644 index 0000000000..3e0bda8023 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-scope-and-functions.spanish.md @@ -0,0 +1,132 @@ +--- +id: 56533eb9ac21ba0edf2244be +title: Global Scope and Functions +localeTitle: Ámbito global y funciones +challengeType: 1 +--- + +## Description +
+En JavaScript, el alcance se refiere a la visibilidad de las variables. Las variables que se definen fuera de un bloque de función tienen alcance global . Esto significa que pueden verse en todas partes en su código JavaScript. +Las variables que se utilizan sin la palabra clave var se crean automáticamente en el ámbito global . Esto puede crear consecuencias no deseadas en otra parte de su código o al ejecutar una función nuevamente. Siempre debes declarar tus variables con var . +
+ +## Instructions +
+Usando var , declare una variable global myGlobal fuera de cualquier función. Inicialízalo con un valor de 10 . +Dentro de la función fun1 , asigne 5 a oopsGlobal sin usar la palabra clave var . +
+ +## Tests +
+ +```yml +tests: + - text: myGlobal debe ser definido + testString: 'assert(typeof myGlobal != "undefined", "myGlobal should be defined");' + - text: myGlobal debe tener un valor de 10 + testString: 'assert(myGlobal === 10, "myGlobal should have a value of 10");' + - text: myGlobal debe declararse usando la palabra clave var + testString: 'assert(/var\s+myGlobal/.test(code), "myGlobal should be declared using the var keyword");' + - text: oopsGlobal debe ser una variable global y tener un valor de 5 + testString: 'assert(typeof oopsGlobal != "undefined" && oopsGlobal === 5, "oopsGlobal should be a global variable and have a value of 5");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Declare your variable here + + +function fun1() { + // Assign 5 to oopsGlobal Here + +} + +// Only change code above this line +function fun2() { + var output = ""; + if (typeof myGlobal != "undefined") { + output += "myGlobal: " + myGlobal; + } + if (typeof oopsGlobal != "undefined") { + output += " oopsGlobal: " + oopsGlobal; + } + console.log(output); +} +``` + +
+ +### Before Test +
+ +```js +var logOutput = ""; +var originalConsole = console +function capture() { + var nativeLog = console.log; + console.log = function (message) { + logOutput = message; + if(nativeLog.apply) { + nativeLog.apply(originalConsole, arguments); + } else { + var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); + nativeLog(nativeMsg); + } + }; +} + +function uncapture() { + console.log = originalConsole.log; +} +var oopsGlobal; +capture(); +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +// Declare your variable here +var myGlobal = 10; + +function fun1() { + // Assign 5 to oopsGlobal Here + oopsGlobal = 5; +} + +// Only change code above this line +function fun2() { + var output = ""; + if(typeof myGlobal != "undefined") { + output += "myGlobal: " + myGlobal; + } + if(typeof oopsGlobal != "undefined") { + output += " oopsGlobal: " + oopsGlobal; + } + console.log(output); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.spanish.md new file mode 100644 index 0000000000..f84d696aa3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/global-vs.-local-scope-in-functions.spanish.md @@ -0,0 +1,76 @@ +--- +id: 56533eb9ac21ba0edf2244c0 +title: Global vs. Local Scope in Functions +localeTitle: Ámbito global vs. local en funciones +challengeType: 1 +--- + +## Description +
+Es posible tener variables locales y globales con el mismo nombre. Cuando haces esto, la variable local tiene prioridad sobre la variable global . +En este ejemplo: +
var someVar = "Hat";
function myFun() {
  var someVar = "Head";
  return someVar;
}
+La función myFun devolverá "Head" porque la versión local de la variable está presente. +
+ +## Instructions +
+Agregue una variable local a la función myOutfit para anular el valor de outerWear con "sweater" . +
+ +## Tests +
+ +```yml +tests: + - text: No cambie el valor de la outerWear global + testString: 'assert(outerWear === "T-Shirt", "Do not change the value of the global outerWear");' + - text: myOutfit debe devolver "sweater" + testString: 'assert(myOutfit() === "sweater", "myOutfit should return "sweater"");' + - text: No cambie la declaración de devolución + testString: 'assert(/return outerWear/.test(code), "Do not change the return statement");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var outerWear = "T-Shirt"; + +function myOutfit() { + // Only change code below this line + + + + // Only change code above this line + return outerWear; +} + +myOutfit(); +``` + +
+ + + +
+ +## Solution +
+ + +```js +var outerWear = "T-Shirt"; +function myOutfit() { + var outerWear = "sweater"; + return outerWear; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.spanish.md new file mode 100644 index 0000000000..69c4bcdfae --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/golf-code.spanish.md @@ -0,0 +1,112 @@ +--- +id: 5664820f61c48e80c9fa476c +title: Golf Code +localeTitle: Codigo de golf +challengeType: 1 +--- + +## Description +
+En el juego de golf, cada hoyo tiene un par significa el número promedio de strokes que se espera que un golfista realice para hundir la bola en un hoyo para completar el juego. Dependiendo de qué tan por encima o par debajo de tus strokes , hay un apodo diferente. +Su función se pasará par y strokes argumentos. Devuelva la cadena correcta de acuerdo con esta tabla que enumera los trazos en orden de prioridad; arriba (más alto) a abajo (más bajo): +
Trazos Regreso
1 "¡Hoyo en uno!"
<= par - 2 "Águila"
par - 1 "Pajarito"
par "Par"
par + 1 "Espectro"
par + 2 "Doble Bogey"
> = par + 3 "¡Vete a casa!"
+par y strokes siempre serán numéricos y positivos. Hemos agregado una matriz de todos los nombres para su conveniencia. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' golfScore(4, 1) debe devolver "Hole-in-one!"' + testString: 'assert(golfScore(4, 1) === "Hole-in-one!", "golfScore(4, 1) should return "Hole-in-one!"");' + - text: ' golfScore(4, 2) debe devolver "Eagle"' + testString: 'assert(golfScore(4, 2) === "Eagle", "golfScore(4, 2) should return "Eagle"");' + - text: ' golfScore(5, 2) debe devolver "Eagle"' + testString: 'assert(golfScore(5, 2) === "Eagle", "golfScore(5, 2) should return "Eagle"");' + - text: ' golfScore(4, 3) debe devolver "Birdie"' + testString: 'assert(golfScore(4, 3) === "Birdie", "golfScore(4, 3) should return "Birdie"");' + - text: ' golfScore(4, 4) debe devolver "Par" + testString: 'assert(golfScore(4, 4) === "Par", "golfScore(4, 4) should return "Par"");' + - text: ' golfScore(1, 1) debe devolver "Hole-in-one!"' + testString: 'assert(golfScore(1, 1) === "Hole-in-one!", "golfScore(1, 1) should return "Hole-in-one!"");' + - text: ' golfScore(5, 5) debe devolver "Par" + testString: 'assert(golfScore(5, 5) === "Par", "golfScore(5, 5) should return "Par"");' + - text: ' golfScore(4, 5) debería devolver "Bogey"' + testString: 'assert(golfScore(4, 5) === "Bogey", "golfScore(4, 5) should return "Bogey"");' + - text: ' golfScore(4, 6) debería devolver "Double Bogey"' + testString: 'assert(golfScore(4, 6) === "Double Bogey", "golfScore(4, 6) should return "Double Bogey"");' + - text: ' golfScore(4, 7) debe devolver "Go Home!"' + testString: 'assert(golfScore(4, 7) === "Go Home!", "golfScore(4, 7) should return "Go Home!"");' + - text: ' golfScore(5, 9) debe devolver "Go Home!"' + testString: 'assert(golfScore(5, 9) === "Go Home!", "golfScore(5, 9) should return "Go Home!"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var names = ["Hole-in-one!", "Eagle", "Birdie", "Par", "Bogey", "Double Bogey", "Go Home!"]; +function golfScore(par, strokes) { + // Only change code below this line + + + return "Change Me"; + // Only change code above this line +} + +// Change these values to test +golfScore(5, 4); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function golfScore(par, strokes) { + if (strokes === 1) { + return "Hole-in-one!"; + } + + if (strokes <= par - 2) { + return "Eagle"; + } + + if (strokes === par - 1) { + return "Birdie"; + } + + if (strokes === par) { + return "Par"; + } + + if (strokes === par + 1) { + return "Bogey"; + } + + if(strokes === par + 2) { + return "Double Bogey"; + } + + return "Go Home!"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.spanish.md new file mode 100644 index 0000000000..f59f3eb16e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/increment-a-number-with-javascript.spanish.md @@ -0,0 +1,77 @@ +--- +id: 56533eb9ac21ba0edf2244ac +title: Increment a Number with JavaScript +localeTitle: Incrementar un número con JavaScript +challengeType: 1 +--- + +## Description +
+Puede incrementar o agregar fácilmente uno a una variable con el operador ++ . +i++; +es el equivalente de +i = i + 1; +Nota
La línea entera se convierte en i++; , eliminando la necesidad del signo igual. +
+ +## Instructions +
+Cambie el código para usar el operador ++ en myVar . +Pista
Obtenga más información sobre los operadores aritméticos - Incremento (++) . +
+ +## Tests +
+ +```yml +tests: + - text: myVar debe ser igual a 88 + testString: 'assert(myVar === 88, "myVar should equal 88");' + - text: myVar = myVar + 1; debería ser cambiado + testString: 'assert(/var\s*myVar\s*=\s*87;\s*\/*.*\s*([+]{2}\s*myVar|myVar\s*[+]{2});/.test(code), "myVar = myVar + 1; should be changed");' + - text: Usa el operador ++ + testString: 'assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code), "Use the ++ operator");' + - text: No cambie el código por encima de la línea + testString: 'assert(/var myVar = 87;/.test(code), "Do not change code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myVar = 87; + +// Only change code below this line +myVar = myVar + 1; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myVar = 87; +myVar++; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator.spanish.md new file mode 100644 index 0000000000..f3f45ee14e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/initializing-variables-with-the-assignment-operator.spanish.md @@ -0,0 +1,67 @@ +--- +id: 56533eb9ac21ba0edf2244a9 +title: Initializing Variables with the Assignment Operator +localeTitle: Inicializando variables con el operador de asignación +challengeType: 1 +--- + +## Description +
+Es común inicializar una variable a un valor inicial en la misma línea que se declara. +var myVar = 0; +Crea una nueva variable llamada myVar y le asigna un valor inicial de 0 . +
+ +## Instructions +
+Defina una variable a con var e inicialícela a un valor de 9 . +
+ +## Tests +
+ +```yml +tests: + - text: Inicializar a a un valor de 9 + testString: 'assert(/var\s+a\s*=\s*9\s*/.test(code), "Initialize a to a value of 9");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourVar = 19; + +// Only change code below this line + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 9; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.spanish.md new file mode 100644 index 0000000000..552833d22a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements.spanish.md @@ -0,0 +1,90 @@ +--- +id: 56533eb9ac21ba0edf2244db +title: Introducing Else If Statements +localeTitle: Introduciendo Else If Sentencias +challengeType: 1 +--- + +## Description +
+Si tiene varias condiciones que deben abordarse, puede encadenar if sentencias junto con else if sent. +
if (num > 15) {
  return "Bigger than 15";
} else if (num < 5) {
  return "Smaller than 5";
} else {
  return "Between 5 and 15";
}
+
+ +## Instructions +
+Convertir la lógica para usar else if instrucciones. +
+ +## Tests +
+ +```yml +tests: + - text: Debes tener al menos dos declaraciones else + testString: 'assert(code.match(/else/g).length > 1, "You should have at least two else statements");' + - text: Debes tener al menos dos declaraciones if + testString: 'assert(code.match(/if/g).length > 1, "You should have at least two if statements");' + - text: Usted debe tener que cerrar y abrir llaves para cada condición + testString: 'assert(code.match(/if\s*\((.+)\)\s*\{[\s\S]+\}\s*else if\s*\((.+)\)\s*\{[\s\S]+\}\s*else\s*\{[\s\S]+\s*\}/), "You should have closing and opening curly braces for each condition in your if else statement");' + - text: testElseIf(0) debería devolver "Más pequeño que 5" + testString: 'assert(testElseIf(0) === "Smaller than 5", "testElseIf(0) should return "Smaller than 5"");' + - text: testElseIf(5) debe devolver "Entre 5 y 10" + testString: 'assert(testElseIf(5) === "Between 5 and 10", "testElseIf(5) should return "Between 5 and 10"");' + - text: testElseIf(7) debe devolver "Entre 5 y 10" + testString: 'assert(testElseIf(7) === "Between 5 and 10", "testElseIf(7) should return "Between 5 and 10"");' + - text: testElseIf(10) debe devolver "Entre 5 y 10" + testString: 'assert(testElseIf(10) === "Between 5 and 10", "testElseIf(10) should return "Between 5 and 10"");' + - text: testElseIf(12) debe devolver "Más de 10" + testString: 'assert(testElseIf(12) === "Greater than 10", "testElseIf(12) should return "Greater than 10"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testElseIf(val) { + if (val > 10) { + return "Greater than 10"; + } + + if (val < 5) { + return "Smaller than 5"; + } + + return "Between 5 and 10"; +} + +// Change this value to test +testElseIf(7); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testElseIf(val) { + if(val > 10) { + return "Greater than 10"; + } else if(val < 5) { + return "Smaller than 5"; + } else { + return "Between 5 and 10"; + } +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.spanish.md new file mode 100644 index 0000000000..c3bbd6fd75 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements.spanish.md @@ -0,0 +1,92 @@ +--- +id: 56533eb9ac21ba0edf2244da +title: Introducing Else Statements +localeTitle: Introduciendo otras declaraciones +challengeType: 1 +--- + +## Description +
+Cuando una condición para una sentencia if es verdadera, se ejecuta el bloque de código siguiente. ¿Qué pasa cuando esa condición es falsa? Normalmente no pasaría nada. Con una sentencia else , se puede ejecutar un bloque de código alternativo. +
if (num > 10) {
  return "Bigger than 10";
} else {
  return "10 or Less";
}
+
+ +## Instructions +
+Combine las sentencias if en una sola sentencia if/else . +
+ +## Tests +
+ +```yml +tests: + - text: Solo debes tener una sentencia if en el editor. + testString: 'assert(code.match(/if/g).length === 1, "You should only have one if statement in the editor");' + - text: Debes usar una sentencia else + testString: 'assert(/else/g.test(code), "You should use an else statement");' + - text: testElse(4) debe devolver "5 o más pequeño" + testString: 'assert(testElse(4) === "5 or Smaller", "testElse(4) should return "5 or Smaller"");' + - text: testElse(5) debe devolver "5 o más pequeño" + testString: 'assert(testElse(5) === "5 or Smaller", "testElse(5) should return "5 or Smaller"");' + - text: testElse(6) debe devolver "Más grande que 5" + testString: 'assert(testElse(6) === "Bigger than 5", "testElse(6) should return "Bigger than 5"");' + - text: testElse(10) debe devolver "Más grande que 5" + testString: 'assert(testElse(10) === "Bigger than 5", "testElse(10) should return "Bigger than 5"");' + - text: No cambie el código por encima o por debajo de las líneas. + testString: 'assert(/var result = "";/.test(code) && /return result;/.test(code), "Do not change the code above or below the lines.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function testElse(val) { + var result = ""; + // Only change code below this line + + if (val > 5) { + result = "Bigger than 5"; + } + + if (val <= 5) { + result = "5 or Smaller"; + } + + // Only change code above this line + return result; +} + +// Change this value to test +testElse(4); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function testElse(val) { + var result = ""; + if(val > 5) { + result = "Bigger than 5"; + } else { + result = "5 or Smaller"; + } + return result; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.spanish.md new file mode 100644 index 0000000000..5be5980846 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-odd-numbers-with-a-for-loop.spanish.md @@ -0,0 +1,86 @@ +--- +id: 56104e9e514f539506016a5c +title: Iterate Odd Numbers With a For Loop +localeTitle: Iterar números impares con un bucle for +challengeType: 1 +--- + +## Description +
+Para que los bucles no tengan que iterar uno a la vez. Al cambiar nuestra final-expression , podemos contar por números pares. +Comenzaremos en i = 0 y haremos un bucle mientras que i < 10 . Incrementaremos i en 2 en cada bucle con i += 2 . +
var ourArray = [];
for (var i = 0; i < 10; i += 2) {
  ourArray.push(i);
}
+ourArray ahora contendrá [0,2,4,6,8] . +Cambiemos nuestra initialization para que podamos contar por números impares. +
+ +## Instructions +
+Empuje los números impares del 1 al 9 a myArray usando un bucle for . +
+ +## Tests +
+ +```yml +tests: + - text: Usted debe estar usando una for bucle para esto. + testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a for loop for this.");' + - text: ' myArray debería ser igual a [1,3,5,7,9] .' + testString: 'assert.deepEqual(myArray, [1,3,5,7,9], "myArray should equal [1,3,5,7,9].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = []; + +for (var i = 0; i < 10; i += 2) { + ourArray.push(i); +} + +// Setup +var myArray = []; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourArray = []; +for (var i = 0; i < 10; i += 2) { + ourArray.push(i); +} +var myArray = []; +for (var i = 1; i < 10; i += 2) { + myArray.push(i); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.spanish.md new file mode 100644 index 0000000000..fe3391260d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-through-an-array-with-a-for-loop.spanish.md @@ -0,0 +1,94 @@ +--- +id: 5675e877dbd60be8ad28edc6 +title: Iterate Through an Array with a For Loop +localeTitle: Iterar a través de una matriz con un bucle For +challengeType: 1 +--- + +## Description +
+Una tarea común en JavaScript es iterar a través del contenido de una matriz. Una forma de hacerlo es con un bucle for . Este código dará salida a cada elemento de la matriz arr a la consola: +
var arr = [10,9,8,7,6];
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}
+Recuerde que las matrices tienen numeración basada en cero, lo que significa que el último índice de la matriz es la longitud - 1. Nuestra condición para este bucle es i < arr.length , que se detiene cuando i tiene la longitud - 1. +
+ +## Instructions +
+Declarar e inicializar una variable total a 0 . Use un bucle for para agregar el valor de cada elemento de la matriz myArr al total . +
+ +## Tests +
+ +```yml +tests: + - text: total debe ser declarado e inicializado a 0 + testString: 'assert(code.match(/var.*?total\s*=\s*0.*?;/), "total should be declared and initialized to 0");' + - text: total debe ser igual a 20 + testString: 'assert(total === 20, "total should equal 20");' + - text: Debe usar un bucle for para iterar a través de myArr + testString: 'assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/), "You should use a for loop to iterate through myArr");' + - text: No establezca el total a 20 directamente + testString: 'assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g), "Do not set total to 20 directly");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArr = [ 9, 10, 11, 12]; +var ourTotal = 0; + +for (var i = 0; i < ourArr.length; i++) { + ourTotal += ourArr[i]; +} + +// Setup +var myArr = [ 2, 3, 4, 5, 6]; + +// Only change code below this line + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourArr = [ 9, 10, 11, 12]; +var ourTotal = 0; + +for (var i = 0; i < ourArr.length; i++) { + ourTotal += ourArr[i]; +} + +var myArr = [ 2, 3, 4, 5, 6]; +var total = 0; + +for (var i = 0; i < myArr.length; i++) { + total += myArr[i]; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.spanish.md new file mode 100644 index 0000000000..5619db08da --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-do...while-loops.spanish.md @@ -0,0 +1,91 @@ +--- +id: 5a2efd662fb457916e1fe604 +title: Iterate with JavaScript Do...While Loops +localeTitle: Iterar con JavaScript Do ... While Loops +challengeType: 1 +--- + +## Description +
+Puede ejecutar el mismo código varias veces utilizando un bucle. +El siguiente tipo de bucle que aprenderá se llama bucle " do...while " porque primero " do " una pasada del código dentro del bucle sin importar qué, y luego se ejecuta " while " una condición específica es verdadero y se detiene una vez que esa condición ya no es verdadera. Veamos un ejemplo. +
var ourArray = [];
var i = 0;
do {
  ourArray.push(i);
  i++;
} while (i < 5);
+Esto se comporta como se esperaría con cualquier otro tipo de bucle, y la matriz resultante se verá como [0, 1, 2, 3, 4] . Sin embargo, lo que hace do...while diferente de otros bucles es cómo se comporta cuando la condición falla en la primera comprobación. Veamos esto en acción. +Aquí hay un bucle while común que ejecutará el código en el bucle siempre y cuando i < 5 . +
var ourArray = [];
var i = 5;
while (i < 5) {
  ourArray.push(i);
  i++;
}
+Observe que inicializamos el valor de i en 5. Cuando ejecutamos la siguiente línea, notamos que i no es menor que 5. Por lo tanto, no ejecutamos el código dentro del bucle. El resultado es que ourArray no agregará nada, por lo que aún se verá así [] cuando todo el código del ejemplo anterior termine de ejecutarse. +Ahora, eche un vistazo a un do...while loop. +
var ourArray = [];
var i = 5;
do {
  ourArray.push(i);
  i++;
} while (i < 5);
+En este caso, inicializamos el valor de i como 5, como hicimos con el bucle while. Cuando llegamos a la siguiente línea, no hay comprobación del valor de i , por lo que vamos al código dentro de las llaves y lo ejecutamos. Agregaremos un elemento a la matriz e incrementaremos i antes de llegar a la verificación de condición. Entonces, cuando se llega a comprobar si i < 5 ver que i es ahora de 6 años, que no pasa la comprobación condicional. Así que salimos del bucle y estamos listos. Al final del ejemplo anterior, el valor de ourArray es [5] . +Esencialmente, un bucle do...while while garantiza que el código dentro del bucle se ejecute al menos una vez. +Intentemos obtener un ciclo do...while while para que funcione presionando los valores en una matriz. +
+ +## Instructions +
+Cambiar el while de bucle en el código a un do...while bucle de modo que el bucle empujará el número 10 a myArray , y i será igual a 11 cuando el código termina de ejecutarse. +
+ +## Tests +
+ +```yml +tests: + - text: Deberías usar un bucle do...while while para esto. + testString: 'assert(code.match(/do/g), "You should be using a do...while loop for this.");' + - text: ' myArray debería ser igual a [10] '. + testString: 'assert.deepEqual(myArray, [10], "myArray should equal [10].");' + - text: i debe ser igual a 11 + testString: 'assert.deepEqual(i, 11, "i should equal 11");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myArray = []; +var i = 10; + +// Only change code below this line. + +while (i < 5) { + myArray.push(i); + i++; +} + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = []; +var i = 10; +do { + myArray.push(i); + i++; +} while (i < 5) +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.spanish.md new file mode 100644 index 0000000000..7ca46ab306 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-for-loops.spanish.md @@ -0,0 +1,91 @@ +--- +id: cf1111c1c11feddfaeb5bdef +title: Iterate with JavaScript For Loops +localeTitle: Iterar con JavaScript para bucles +challengeType: 1 +--- + +## Description +
+Puede ejecutar el mismo código varias veces utilizando un bucle. +El tipo más común de bucle de JavaScript se llama " for loop " porque se ejecuta "por" un número específico de veces. +Para los bucles se declaran con tres expresiones opcionales separadas por punto y coma: +for ([initialization]; [condition]; [final-expression]) +La instrucción de initialization se ejecuta una sola vez antes de que comience el bucle. Normalmente se utiliza para definir y configurar su variable de bucle. +La declaración de condition se evalúa al comienzo de cada iteración de bucle y continuará mientras se evalúe como true . Cuando la condition es false al inicio de la iteración, el bucle dejará de ejecutarse. Esto significa que si la condition comienza como false , su bucle nunca se ejecutará. +La final-expression se ejecuta al final de cada iteración de bucle, antes de la siguiente verificación de condition y generalmente se usa para aumentar o disminuir su contador de bucle. +En el siguiente ejemplo, inicializamos con i = 0 e iteramos mientras nuestra condición i < 5 es verdadera. Incrementaremos i en 1 en cada iteración de bucle con i++ como nuestra final-expression . +
var ourArray = [];
for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}
+ourArray ahora contendrá [0,1,2,3,4] . +
+ +## Instructions +
+Use un bucle for para trabajar y empujar los valores del 1 al 5 en myArray . +
+ +## Tests +
+ +```yml +tests: + - text: Usted debe estar usando una for bucle para esto. + testString: 'assert(code.match(/for\s*\(/g).length > 1, "You should be using a for loop for this.");' + - text: ' myArray debe ser igual a [1,2,3,4,5] .' + testString: 'assert.deepEqual(myArray, [1,2,3,4,5], "myArray should equal [1,2,3,4,5].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = []; + +for (var i = 0; i < 5; i++) { + ourArray.push(i); +} + +// Setup +var myArray = []; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var ourArray = []; +for (var i = 0; i < 5; i++) { + ourArray.push(i); +} +var myArray = []; +for (var i = 1; i < 6; i++) { + myArray.push(i); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.spanish.md new file mode 100644 index 0000000000..ecf890f5df --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/iterate-with-javascript-while-loops.spanish.md @@ -0,0 +1,76 @@ +--- +id: cf1111c1c11feddfaeb1bdef +title: Iterate with JavaScript While Loops +localeTitle: Iterar con JavaScript mientras bucles +challengeType: 1 +--- + +## Description +
+Puede ejecutar el mismo código varias veces utilizando un bucle. +El primer tipo de bucle vamos a aprender se llama un " while " bucle porque funciona "mientras que" una condición especificada es verdadera y se detiene una vez que la condición ya no es cierto. +
var ourArray = [];
var i = 0;
while(i < 5) {
  ourArray.push(i);
  i++;
}
+Intentemos que funcione un bucle while empujando los valores a una matriz. +
+ +## Instructions +
+Empuje los números de 0 a 4 para myArray usando un while de bucle. +
+ +## Tests +
+ +```yml +tests: + - text: Usted debe utilizar un while de bucle para esto. + testString: 'assert(code.match(/while/g), "You should be using a while loop for this.");' + - text: ' myArray debe ser igual a [0,1,2,3,4] .' + testString: 'assert.deepEqual(myArray, [0,1,2,3,4], "myArray should equal [0,1,2,3,4].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myArray = []; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = []; +var i = 0; +while(i < 5) { + myArray.push(i); + i++; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.spanish.md new file mode 100644 index 0000000000..d144c75e58 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/local-scope-and-functions.spanish.md @@ -0,0 +1,111 @@ +--- +id: 56533eb9ac21ba0edf2244bf +title: Local Scope and Functions +localeTitle: Ámbito local y funciones +challengeType: 1 +--- + +## Description +
+Las variables que se declaran dentro de una función, así como los parámetros de la función tienen alcance local . Eso significa que, sólo son visibles dentro de esa función. +Aquí hay una función myTest con una variable local llamada loc . +
function myTest() {
  var loc = "foo";
  console.log(loc);
}
myTest(); // logs "foo"
console.log(loc); // loc is not defined
+loc no está definido fuera de la función. +
+ +## Instructions +
+Declare una variable local myVar dentro de myLocalScope . Ejecute las pruebas y luego siga las instrucciones comentadas en el editor. +Pista
Actualizar la página puede ayudar si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: Ninguna variable global myVar + testString: 'assert(typeof myVar === "undefined", "No global myVar variable");' + - text: Agrega una variable myVar local + testString: 'assert(/var\s+myVar/.test(code), "Add a local myVar variable");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function myLocalScope() { + 'use strict'; // you shouldn't need to edit this line + + console.log(myVar); +} +myLocalScope(); + +// Run and check the console +// myVar is not defined outside of myLocalScope +console.log(myVar); + +// Now remove the console log line to pass the test + +``` + +
+ +### Before Test +
+ +```js +var logOutput = ""; +var originalConsole = console +function capture() { + var nativeLog = console.log; + console.log = function (message) { + logOutput = message; + if(nativeLog.apply) { + nativeLog.apply(originalConsole, arguments); + } else { + var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); + nativeLog(nativeMsg); + } + }; +} + +function uncapture() { + console.log = originalConsole.log; +} + +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function myLocalScope() { + 'use strict'; + + var myVar; + console.log(myVar); +} +myLocalScope(); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.spanish.md new file mode 100644 index 0000000000..c1d6a4df0c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/logical-order-in-if-else-statements.spanish.md @@ -0,0 +1,84 @@ +--- +id: 5690307fddb111c6084545d7 +title: Logical Order in If Else Statements +localeTitle: Orden lógico en si otras declaraciones +challengeType: 1 +--- + +## Description +
+orden es importante en if , else if declaraciones. +La función se ejecuta de arriba a abajo, por lo que deberá tener cuidado con la afirmación que aparece primero. +Toma estas dos funciones como ejemplo. +Aquí está el primero: +
function foo(x) {
  if (x < 1) {
    return "Less than one";
  } else if (x < 2) {
    return "Less than two";
  } else {
    return "Greater than or equal to two";
  }
}
+Y el segundo solo cambia el orden de las declaraciones: +
function bar(x) {
  if (x < 2) {
    return "Less than two";
  } else if (x < 1) {
    return "Less than one";
  } else {
    return "Greater than or equal to two";
  }
}
+Si bien estas dos funciones parecen casi idénticas, si pasamos un número a ambas obtenemos diferentes salidas. +
foo(0) // "Less than one"
bar(0) // "Less than two"
+
+ +## Instructions +
+Cambie el orden de la lógica en la función para que devuelva las declaraciones correctas en todos los casos. +
+ +## Tests +
+ +```yml +tests: + - text: orderMyLogic(4) debe devolver "Menos de 5" + testString: 'assert(orderMyLogic(4) === "Less than 5", "orderMyLogic(4) should return "Less than 5"");' + - text: orderMyLogic(6) debe devolver "Menos de 10" + testString: 'assert(orderMyLogic(6) === "Less than 10", "orderMyLogic(6) should return "Less than 10"");' + - text: orderMyLogic(11) debe devolver "Mayor o igual a 10" + testString: 'assert(orderMyLogic(11) === "Greater than or equal to 10", "orderMyLogic(11) should return "Greater than or equal to 10"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function orderMyLogic(val) { + if (val < 10) { + return "Less than 10"; + } else if (val < 5) { + return "Less than 5"; + } else { + return "Greater than or equal to 10"; + } +} + +// Change this value to test +orderMyLogic(7); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function orderMyLogic(val) { + if(val < 5) { + return "Less than 5"; + } else if (val < 10) { + return "Less than 10"; + } else { + return "Greater than or equal to 10"; + } +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.spanish.md new file mode 100644 index 0000000000..a3d9689ff9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-pop.spanish.md @@ -0,0 +1,80 @@ +--- +id: 56bbb991ad1ed5201cd392cc +title: Manipulate Arrays With pop() +localeTitle: Manipular matrices con pop () +challengeType: 1 +--- + +## Description +
+Otra forma de cambiar los datos en una matriz es con la función .pop() . +.pop() se usa para " .pop() " un valor del final de una matriz. Podemos almacenar este valor "extraído" asignándolo a una variable. En otras palabras, .pop() elimina el último elemento de una matriz y devuelve ese elemento. +Cualquier tipo de entrada se puede "extraer" de una matriz: números, cadenas, incluso matrices anidadas. +
var threeArr = [1, 4, 6];
var oneDown = threeArr.pop();
console.log(oneDown); // Returns 6
console.log(threeArr); // Returns [1, 4]
+
+ +## Instructions +
+Use la función .pop() para eliminar el último elemento de myArray , asignando el valor de "desprendimiento de" a removedFromMyArray . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray solo debe contener [["John", 23]] .' + testString: 'assert((function(d){if(d[0][0] == "John" && d[0][1] === 23 && d[1] == undefined){return true;}else{return false;}})(myArray), "myArray should only contain [["John", 23]].");' + - text: Usa pop() en myArray + testString: 'assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code), "Use pop() on myArray");' + - text: ' removedFromMyArray solo debe contener ["cat", 2] .' + testString: 'assert((function(d){if(d[0] == "cat" && d[1] === 2 && d[2] == undefined){return true;}else{return false;}})(removedFromMyArray), "removedFromMyArray should only contain ["cat", 2].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = [1,2,3]; +var removedFromOurArray = ourArray.pop(); +// removedFromOurArray now equals 3, and ourArray now equals [1,2] + +// Setup +var myArray = [["John", 23], ["cat", 2]]; + +// Only change code below this line. +var removedFromMyArray; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [["John", 23], ["cat", 2]]; +var removedFromMyArray = myArray.pop(); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.spanish.md new file mode 100644 index 0000000000..dcbe23fcb3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-push.spanish.md @@ -0,0 +1,74 @@ +--- +id: 56bbb991ad1ed5201cd392cb +title: Manipulate Arrays With push() +localeTitle: Manipular matrices con empuje () +challengeType: 1 +--- + +## Description +
+Una forma fácil de agregar datos al final de una matriz es a través de la función push() . +.push() toma uno o más parámetros y los "empuja" al final de la matriz. +
var arr = [1,2,3];
arr.push(4);
// arr is now [1,2,3,4]
+
+ +## Instructions +
+Presione ["dog", 3] en el extremo de la variable myArray . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray ahora debe ser igual a [["John", 23], ["cat", 2], ["dog", 3]] .' + testString: 'assert((function(d){if(d[2] != undefined && d[0][0] == "John" && d[0][1] === 23 && d[2][0] == "dog" && d[2][1] === 3 && d[2].length == 2){return true;}else{return false;}})(myArray), "myArray should now equal [["John", 23], ["cat", 2], ["dog", 3]].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = ["Stimpson", "J", "cat"]; +ourArray.push(["happy", "joy"]); +// ourArray now equals ["Stimpson", "J", "cat", ["happy", "joy"]] + +// Setup +var myArray = [["John", 23], ["cat", 2]]; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [["John", 23], ["cat", 2]]; +myArray.push(["dog",3]); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.spanish.md new file mode 100644 index 0000000000..49e48d9d54 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-shift.spanish.md @@ -0,0 +1,78 @@ +--- +id: 56bbb991ad1ed5201cd392cd +title: Manipulate Arrays With shift() +localeTitle: Manipular matrices con cambio () +challengeType: 1 +--- + +## Description +
+pop() siempre elimina el último elemento de una matriz. ¿Qué pasa si quieres eliminar el primero? +Ahí es donde .shift() en .shift() . Funciona igual que .pop() , excepto que elimina el primer elemento en lugar del último. +
+ +## Instructions +
+Use la función .shift() para eliminar el primer elemento de myArray , asignando el valor "desviado" a removedFromMyArray . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray ahora debe ser igual a [["dog", 3]] .' + testString: 'assert((function(d){if(d[0][0] == "dog" && d[0][1] === 3 && d[1] == undefined){return true;}else{return false;}})(myArray), "myArray should now equal [["dog", 3]].");' + - text: ' removedFromMyArray debe contener ["John", 23] .' + testString: 'assert((function(d){if(d[0] == "John" && d[1] === 23 && typeof removedFromMyArray === "object"){return true;}else{return false;}})(removedFromMyArray), "removedFromMyArray should contain ["John", 23].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = ["Stimpson", "J", ["cat"]]; +var removedFromOurArray = ourArray.shift(); +// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]]. + +// Setup +var myArray = [["John", 23], ["dog", 3]]; + +// Only change code below this line. +var removedFromMyArray; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [["John", 23], ["dog", 3]]; + +// Only change code below this line. +var removedFromMyArray = myArray.shift(); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.spanish.md new file mode 100644 index 0000000000..cb813bc690 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulate-arrays-with-unshift.spanish.md @@ -0,0 +1,76 @@ +--- +id: 56bbb991ad1ed5201cd392ce +title: Manipulate Arrays With unshift() +localeTitle: Manipular matrices con unshift () +challengeType: 1 +--- + +## Description +
+No solo puede shift elementos del principio de una matriz, unshift también puede unshift elementos al principio de una matriz, es decir, agregar elementos delante de la matriz. +.unshift() funciona exactamente como .push() , pero en lugar de agregar el elemento al final de la matriz, unshift() agrega el elemento al principio de la matriz. +
+ +## Instructions +
+Añadir ["Paul",35] para el inicio de la myArray variable usando unshift() . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray debería tener ahora [["Paul", 35], ["dog", 3]].' + testString: 'assert((function(d){if(typeof d[0] === "object" && d[0][0] == "Paul" && d[0][1] === 35 && d[1][0] != undefined && d[1][0] == "dog" && d[1][1] != undefined && d[1][1] == 3){return true;}else{return false;}})(myArray), "myArray should now have [["Paul", 35], ["dog", 3]].");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = ["Stimpson", "J", "cat"]; +ourArray.shift(); // ourArray now equals ["J", "cat"] +ourArray.unshift("Happy"); +// ourArray now equals ["Happy", "J", "cat"] + +// Setup +var myArray = [["John", 23], ["dog", 3]]; +myArray.shift(); + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [["John", 23], ["dog", 3]]; +myArray.shift(); +myArray.unshift(["Paul", 35]); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.spanish.md new file mode 100644 index 0000000000..0268df122c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects.spanish.md @@ -0,0 +1,120 @@ +--- +id: 56533eb9ac21ba0edf2244cb +title: Manipulating Complex Objects +localeTitle: Manipulando objetos complejos +challengeType: 1 +--- + +## Description +
+A veces es posible que desee almacenar datos en una estructura de datos flexible. Un objeto JavaScript es una forma de manejar datos flexibles. Permiten combinaciones arbitrarias de cadenas , números , booleanos , matrices , funciones y objetos . +Aquí hay un ejemplo de una estructura de datos compleja: +
var ourMusic = [
  {
    "artist": "Daft Punk",
    "title": "Homework",
    "release_year": 1997,
    "formats": [
      "CD",
      "Cassette",
      "LP"
    ],
    "gold": true
  }
];
+Esta es una matriz que contiene un objeto dentro. El objeto tiene varias piezas de metadatos sobre un álbum. También tiene una matriz de "formats" anidados. Si desea agregar más registros de álbum, puede hacerlo agregando registros a la matriz de nivel superior. +objetos contienen datos en una propiedad, que tiene un formato de clave-valor. En el ejemplo anterior, "artist": "Daft Punk" es una propiedad que tiene una clave de "artist" y un valor de "Daft Punk" . +JavaScript Object Notation o JSON es un formato de intercambio de datos relacionado que se utiliza para almacenar datos. +
{
  "artist": "Daft Punk",
  "title": "Homework",
  "release_year": 1997,
  "formats": [
    "CD",
    "Cassette",
    "LP"
  ],
  "gold": true
}
+Nota
Deberá colocar una coma después de cada objeto de la matriz, a menos que sea el último objeto de la matriz. +
+ +## Instructions +
+Agrega un nuevo álbum a la matriz myMusic . Agregue cadenas de artist y title , número de año de release_year y una matriz de formats de cadenas. +
+ +## Tests +
+ +```yml +tests: + - text: myMusic debería ser una matriz + testString: 'assert(Array.isArray(myMusic), "myMusic should be an array");' + - text: myMusic debería tener al menos dos elementos + testString: 'assert(myMusic.length > 1, "myMusic should have at least two elements");' + - text: ' myMusic[1] debería ser un objeto' + testString: 'assert(typeof myMusic[1] === "object", "myMusic[1] should be an object");' + - text: ' myMusic[1] debería tener al menos 4 propiedades' + testString: 'assert(Object.keys(myMusic[1]).length > 3, "myMusic[1] should have at least 4 properties");' + - text: ' myMusic[1] debe contener una propiedad de artist que es una cadena' + testString: 'assert(myMusic[1].hasOwnProperty("artist") && typeof myMusic[1].artist === "string", "myMusic[1] should contain an artist property which is a string");' + - text: ' myMusic[1] debe contener una propiedad de title que es una cadena' + testString: 'assert(myMusic[1].hasOwnProperty("title") && typeof myMusic[1].title === "string", "myMusic[1] should contain a title property which is a string");' + - text: ' myMusic[1] debe contener una propiedad release_year que es un número' + testString: 'assert(myMusic[1].hasOwnProperty("release_year") && typeof myMusic[1].release_year === "number", "myMusic[1] should contain a release_year property which is a number");' + - text: ' myMusic[1] debe contener una propiedad de formats que es una matriz' + testString: 'assert(myMusic[1].hasOwnProperty("formats") && Array.isArray(myMusic[1].formats), "myMusic[1] should contain a formats property which is an array");' + - text: formats deben ser una matriz de cadenas con al menos dos elementos. + testString: 'assert(myMusic[1].formats.every(function(item) { return (typeof item === "string")}) && myMusic[1].formats.length > 1, "formats should be an array of strings with at least two elements");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myMusic = [ + { + "artist": "Billy Joel", + "title": "Piano Man", + "release_year": 1973, + "formats": [ + "CD", + "8T", + "LP" + ], + "gold": true + } + // Add record here +]; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myMusic = [ + { + "artist": "Billy Joel", + "title": "Piano Man", + "release_year": 1973, + "formats": [ + "CS", + "8T", + "LP" ], + "gold": true + }, + { + "artist": "ABBA", + "title": "Ring Ring", + "release_year": 1973, + "formats": [ + "CS", + "8T", + "LP", + "CD", + ] + } +]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.spanish.md new file mode 100644 index 0000000000..13df009d56 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/modify-array-data-with-indexes.spanish.md @@ -0,0 +1,76 @@ +--- +id: cf1111c1c11feddfaeb8bdef +title: Modify Array Data With Indexes +localeTitle: Modificar datos de matriz con índices +challengeType: 1 +--- + +## Description +
+A diferencia de las cadenas, las entradas de matrices son mutables y se pueden cambiar libremente. +Ejemplo +
var ourArray = [50,40,30];
ourArray[0] = 15; // equals [15,40,30]
+Nota
No debe haber espacios entre el nombre de la matriz y los corchetes, como la array [0] . Aunque JavaScript puede procesar esto correctamente, esto puede confundir a otros programadores que leen su código. +
+ +## Instructions +
+Modifique los datos almacenados en el índice 0 de myArray a un valor de 45 . +
+ +## Tests +
+ +```yml +tests: + - text: ' myArray ahora debería ser [45,64,99].' + testString: 'assert((function(){if(typeof myArray != "undefined" && myArray[0] == 45 && myArray[1] == 64 && myArray[2] == 99){return true;}else{return false;}})(), "myArray should now be [45,64,99].");' + - text: Debe utilizar el índice correcto para modificar el valor en myArray . + testString: 'assert((function(){if(code.match(/myArray\[0\]\s*=\s*/g)){return true;}else{return false;}})(), "You should be using correct index to modify the value in myArray.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = [18,64,99]; +ourArray[1] = 45; // ourArray now equals [18,45,99]. + +// Setup +var myArray = [18,64,99]; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [18,64,99]; +myArray[0] = 45; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.spanish.md new file mode 100644 index 0000000000..77b0fb3bda --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements.spanish.md @@ -0,0 +1,109 @@ +--- +id: 56533eb9ac21ba0edf2244df +title: Multiple Identical Options in Switch Statements +localeTitle: Múltiples opciones idénticas en declaraciones de cambio +challengeType: 1 +--- + +## Description +
+Si la sentencia de break se omite en el case de una sentencia de switch , se ejecutan las siguientes sentencias de case hasta que se encuentra una break . Si tiene varias entradas con la misma salida, puede representarlas en una declaración de switch como esta: +
switch(val) {
  case 1:
  case 2:
  case 3:
    result = "1, 2, or 3";
    break;
  case 4:
    result = "4 alone";
}
+casos para 1, 2 y 3 producirán el mismo resultado. +
+ +## Instructions +
+Escriba una instrucción de cambio para establecer la answer para los siguientes rangos:
1-3 - "Bajo"
4-6 - "Mid"
7-9 - "Alta" +Nota
Deberá tener una declaración de case para cada número en el rango. +
+ +## Tests +
+ +```yml +tests: + - text: sequentialSizes(1) debe devolver "Low" + testString: 'assert(sequentialSizes(1) === "Low", "sequentialSizes(1) should return "Low"");' + - text: sequentialSizes(2) debe devolver "Low" + testString: 'assert(sequentialSizes(2) === "Low", "sequentialSizes(2) should return "Low"");' + - text: sequentialSizes(3) debe devolver "Low" + testString: 'assert(sequentialSizes(3) === "Low", "sequentialSizes(3) should return "Low"");' + - text: sequentialSizes(4) debe devolver "Mid" + testString: 'assert(sequentialSizes(4) === "Mid", "sequentialSizes(4) should return "Mid"");' + - text: sequentialSizes(5) debe devolver "Mid" + testString: 'assert(sequentialSizes(5) === "Mid", "sequentialSizes(5) should return "Mid"");' + - text: sequentialSizes(6) debe devolver "Mid" + testString: 'assert(sequentialSizes(6) === "Mid", "sequentialSizes(6) should return "Mid"");' + - text: sequentialSizes(7) debe devolver "Alto" + testString: 'assert(sequentialSizes(7) === "High", "sequentialSizes(7) should return "High"");' + - text: sequentialSizes(8) debe devolver "Alto" + testString: 'assert(sequentialSizes(8) === "High", "sequentialSizes(8) should return "High"");' + - text: sequentialSizes(9) debe devolver "Alto" + testString: 'assert(sequentialSizes(9) === "High", "sequentialSizes(9) should return "High"");' + - text: No debes usar ninguna declaración if o else + testString: 'assert(!/else/g.test(code) || !/if/g.test(code), "You should not use any if or else statements");' + - text: Usted debe tener nueve declaraciones de case + testString: 'assert(code.match(/case/g).length === 9, "You should have nine case statements");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function sequentialSizes(val) { + var answer = ""; + // Only change code below this line + + + + // Only change code above this line + return answer; +} + +// Change this value to test +sequentialSizes(1); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function sequentialSizes(val) { + var answer = ""; + + switch(val) { + case 1: + case 2: + case 3: + answer = "Low"; + break; + case 4: + case 5: + case 6: + answer = "Mid"; + break; + case 7: + case 8: + case 9: + answer = "High"; + } + + return answer; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript.spanish.md new file mode 100644 index 0000000000..1b8f9c5d56 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-decimals-with-javascript.spanish.md @@ -0,0 +1,66 @@ +--- +id: bd7993c9c69feddfaeb7bdef +title: Multiply Two Decimals with JavaScript +localeTitle: Multiplica dos decimales con JavaScript +challengeType: 1 +--- + +## Description +
+En JavaScript, también puede realizar cálculos con números decimales, al igual que los números enteros. +Multipliquemos dos decimales para obtener su producto. +
+ +## Instructions +
+Cambie el 0.0 para que el producto sea igual a 5.0 . +
+ +## Tests +
+ +```yml +tests: + - text: El product variable debe ser igual a 5.0 . + testString: 'assert(product === 5.0, "The variable product should equal 5.0.");' + - text: Debes usar el operador * + testString: 'assert(/\*/.test(code), "You should use the * operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var product = 2.0 * 0.0; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var product = 2.0 * 2.5; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.spanish.md new file mode 100644 index 0000000000..0d5484fd10 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/multiply-two-numbers-with-javascript.spanish.md @@ -0,0 +1,70 @@ +--- +id: cf1231c1c11feddfaeb5bdef +title: Multiply Two Numbers with JavaScript +localeTitle: Multiplica dos números con JavaScript +challengeType: 1 +--- + +## Description +
+También podemos multiplicar un número por otro. +JavaScript usa el símbolo * para la multiplicación de dos números. + +Ejemplo +
myVar = 13 * 13; // assigned 169
+ +
+ +## Instructions +
+Cambia el 0 para que el producto sea igual a 80 . +
+ +## Tests +
+ +```yml +tests: + - text: Hacer que el product variable sea igual a 80. + testString: 'assert(product === 80,"Make the variable product equal 80");' + - text: Usa el operador * + testString: 'assert(/\*/.test(code), "Use the * operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var product = 8 * 0; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var product = 8 * 10; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.spanish.md new file mode 100644 index 0000000000..043c7d4484 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nest-one-array-within-another-array.spanish.md @@ -0,0 +1,65 @@ +--- +id: cf1111c1c11feddfaeb7bdef +title: Nest one Array within Another Array +localeTitle: Anidar una matriz dentro de otra matriz +challengeType: 1 +--- + +## Description +
+También puede anidar matrices dentro de otras matrices, como esta: [["Bulls", 23], ["White Sox", 45]] . Esto también se llama una matriz multidimensional . 0
+ +## Instructions +
+Crea una matriz anidada llamada myArray . +
+ +## Tests +
+ +```yml +tests: + - text: myArray debe tener al menos una matriz anidada dentro de otra matriz. + testString: 'assert(Array.isArray(myArray) && myArray.some(Array.isArray), "myArray should have at least one array nested within another array.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = [["the universe", 42], ["everything", 101010]]; + +// Only change code below this line. +var myArray = []; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = [[1,2,3]]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.spanish.md new file mode 100644 index 0000000000..cb0dcb83d7 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/nesting-for-loops.spanish.md @@ -0,0 +1,79 @@ +--- +id: 56533eb9ac21ba0edf2244e1 +title: Nesting For Loops +localeTitle: Anidando para bucles +challengeType: 1 +--- + +## Description +
+Si tiene una matriz multidimensional, puede usar la misma lógica que el punto de ruta anterior para recorrer tanto la matriz como cualquier subarreglo. Aquí hay un ejemplo: +
var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}
+Esto genera cada subelemento en arr uno a la vez. Tenga en cuenta que para el bucle interno, estamos comprobando la .length de arr[i] , ya que arr[i] es en sí misma una matriz. +
+ +## Instructions +
+Modificar la función multiplyAll para que multiplique la variable del product por cada número en las subarreglas de arr +
+ +## Tests +
+ +```yml +tests: + - text: ' multiplyAll([[1],[2],[3]]) debe devolver 6 ' + testString: 'assert(multiplyAll([[1],[2],[3]]) === 6, "multiplyAll([[1],[2],[3]]) should return 6");' + - text: ' multiplyAll([[1,2],[3,4],[5,6,7]]) debe devolver 5040 ' + testString: 'assert(multiplyAll([[1,2],[3,4],[5,6,7]]) === 5040, "multiplyAll([[1,2],[3,4],[5,6,7]]) should return 5040");' + - text: ' multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) debe devolver 54 ' + testString: 'assert(multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) === 54, "multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]]) should return 54");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function multiplyAll(arr) { + var product = 1; + // Only change code below this line + + // Only change code above this line + return product; +} + +// Modify values below to test your code +multiplyAll([[1,2],[3,4],[5,6,7]]); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function multiplyAll(arr) { + var product = 1; + for (var i = 0; i < arr.length; i++) { + for (var j = 0; j < arr[i].length; j++) { + product *= arr[i][j]; + } + } + return product; +} + +multiplyAll([[1,2],[3,4],[5,6,7]]); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.spanish.md new file mode 100644 index 0000000000..a7d191a995 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.spanish.md @@ -0,0 +1,110 @@ +--- +id: 56533eb9ac21ba0edf2244bd +title: Passing Values to Functions with Arguments +localeTitle: Pasando valores a funciones con argumentos +challengeType: 1 +--- + +## Description +
+parámetros son variables que actúan como marcadores de posición para los valores que deben ingresarse en una función cuando se llama. Cuando se define una función, normalmente se define junto con uno o más parámetros. Los valores reales que se ingresan (o "pasan" ) en una función cuando se llama se conocen como argumentos . +Aquí hay una función con dos parámetros, param1 y param2 : +
function testFun(param1, param2) {
  console.log(param1, param2);
}
+Entonces podemos llamar a testFun : +testFun("Hello", "World"); +Hemos pasado dos argumentos, "Hello" y "World" . Dentro de la función, param1 será igual a "Hello" y param2 será igual a "World". Tenga en cuenta que podría testFun llamar a testFun con diferentes argumentos y los parámetros tomarían el valor de los nuevos argumentos. +
+ +## Instructions +
+
  1. Cree una función llamada functionWithArgs que acepte dos argumentos y envíe su suma a la consola dev.
  2. Llame a la función con dos números como argumentos.
+
+ +## Tests +
+ +```yml +tests: + - text: functionWithArgs debería ser una función + testString: 'assert(typeof functionWithArgs === "function", "functionWithArgs should be a function");' + - text: ' functionWithArgs(1,2) debe generar 3 ' + testString: 'if(typeof functionWithArgs === "function") { capture(); functionWithArgs(1,2); uncapture(); } assert(logOutput == 3, "functionWithArgs(1,2) should output 3");' + - text: ' functionWithArgs(7,9) debe generar 16 ' + testString: 'if(typeof functionWithArgs === "function") { capture(); functionWithArgs(7,9); uncapture(); } assert(logOutput == 16, "functionWithArgs(7,9) should output 16");' + - text: Llame a functionWithArgs con dos números después de definirlo. + testString: 'assert(/^\s*functionWithArgs\s*\(\s*\d+\s*,\s*\d+\s*\)\s*;/m.test(code), "Call functionWithArgs with two numbers after you define it.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +function ourFunctionWithArgs(a, b) { + console.log(a - b); +} +ourFunctionWithArgs(10, 5); // Outputs 5 + +// Only change code below this line. + + +``` + +
+ +### Before Test +
+ +```js +var logOutput = ""; +var originalConsole = console +function capture() { + var nativeLog = console.log; + console.log = function (message) { + if(message) logOutput = JSON.stringify(message).trim(); + if(nativeLog.apply) { + nativeLog.apply(originalConsole, arguments); + } else { + var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); + nativeLog(nativeMsg); + } + }; +} + +function uncapture() { + console.log = originalConsole.log; +} + +capture(); +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function functionWithArgs(a, b) { + console.log(a + b); +} +functionWithArgs(10, 5); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.spanish.md new file mode 100644 index 0000000000..8fa0ad0eb5 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/practice-comparing-different-values.spanish.md @@ -0,0 +1,76 @@ +--- +id: 599a789b454f2bbd91a3ff4d +title: Practice comparing different values +localeTitle: Practicar comparando valores diferentes. +challengeType: 1 +--- + +## Description +
+En los últimos dos desafíos, aprendimos sobre el operador de igualdad ( == ) y el operador de igualdad estricta ( === ). Hagamos una revisión rápida y practiquemos el uso de estos operadores un poco más. +Si los valores que se comparan no son del mismo tipo, el operador de igualdad realizará una conversión de tipo y luego evaluará los valores. Sin embargo, el operador de igualdad estricta comparará tanto el tipo de datos como el valor tal como está, sin convertir un tipo en otro. +ejemplos +
3 == '3' // returns true because JavaScript performs type conversion from string to number
3 === '3' // returns false because the types are different and type conversion is not performed
+Nota
En JavaScript, puede determinar el tipo de una variable o un valor con el operador typeof , de la siguiente manera: +
typeof 3 // returns 'number'
typeof '3' // returns 'string'
+
+ +## Instructions +
+La función compareEquality en el editor compara dos valores utilizando el equality operator . Modifique la función de modo que devuelva "Igual" solo cuando los valores sean estrictamente iguales. +
+ +## Tests +
+ +```yml +tests: + - text: ' compareEquality(10, "10") debe devolver "Not Equal"' + testString: 'assert(compareEquality(10, "10") === "Not Equal", "compareEquality(10, "10") should return "Not Equal"");' + - text: ' compareEquality("20", 20) debe devolver "Not Equal"' + testString: 'assert(compareEquality("20", 20) === "Not Equal", "compareEquality("20", 20) should return "Not Equal"");' + - text: Debes usar el operador === + testString: 'assert(code.match(/===/g), "You should use the === operator");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function compareEquality(a, b) { + if (a == b) { // Change this line + return "Equal"; + } + return "Not Equal"; +} + +// Change this value to test +compareEquality(10, "10"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function compareEquality(a,b) { + if (a === b) { + return "Equal"; + } + return "Not Equal"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.spanish.md new file mode 100644 index 0000000000..59cbf207ea --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.spanish.md @@ -0,0 +1,143 @@ +--- +id: 5688e62ea601b2482ff8422b +title: Profile Lookup +localeTitle: Búsqueda de perfiles +challengeType: 1 +--- + +## Description +
+Tenemos una variedad de objetos que representan a diferentes personas en nuestras listas de contactos. +Se ha lookUpProfile función lookUpProfile que toma el name y una propiedad ( prop ) como argumentos. +La función debe comprobar si name es de un contacto real firstName y la propiedad dada ( prop ) es una propiedad de ese contacto. +Si ambos son verdaderos, devuelva el "valor" de esa propiedad. +Si el name no corresponde a ningún contacto, devuelva "No such contact" +Si la prop no corresponde a ninguna propiedad válida de un contacto encontrado para coincidir con el name entonces devuelva "No such property" existe "No such property" +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' "Kristian", "lastName" debería devolver "Vos" ' + testString: 'assert(lookUpProfile("Kristian","lastName") === "Vos", ""Kristian", "lastName" should return "Vos"");' + - text: ' "Sherlock", "likes" debería devolver ["Intriguing Cases", "Violin"] ' + testString: 'assert.deepEqual(lookUpProfile("Sherlock", "likes"), ["Intriguing Cases", "Violin"], ""Sherlock", "likes" should return ["Intriguing Cases", "Violin"]");' + - text: ' "Harry","likes" debería devolver una matriz' + testString: 'assert(typeof lookUpProfile("Harry", "likes") === "object", ""Harry","likes" should return an array");' + - text: ' "Bob", "number" debe devolver "No existe tal contacto"' + testString: 'assert(lookUpProfile("Bob", "number") === "No such contact", ""Bob", "number" should return "No such contact"");' + - text: ' "Bob", "potato" debe devolver "No hay tal contacto"' + testString: 'assert(lookUpProfile("Bob", "potato") === "No such contact", ""Bob", "potato" should return "No such contact"");' + - text: ' "Akira", "address" debe devolver "No existe tal propiedad" + testString: 'assert(lookUpProfile("Akira", "address") === "No such property", ""Akira", "address" should return "No such property"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +//Setup +var contacts = [ + { + "firstName": "Akira", + "lastName": "Laine", + "number": "0543236543", + "likes": ["Pizza", "Coding", "Brownie Points"] + }, + { + "firstName": "Harry", + "lastName": "Potter", + "number": "0994372684", + "likes": ["Hogwarts", "Magic", "Hagrid"] + }, + { + "firstName": "Sherlock", + "lastName": "Holmes", + "number": "0487345643", + "likes": ["Intriguing Cases", "Violin"] + }, + { + "firstName": "Kristian", + "lastName": "Vos", + "number": "unknown", + "likes": ["JavaScript", "Gaming", "Foxes"] + } +]; + + +function lookUpProfile(name, prop){ +// Only change code below this line + +// Only change code above this line +} + +// Change these values to test your function +lookUpProfile("Akira", "likes"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +var contacts = [ + { + "firstName": "Akira", + "lastName": "Laine", + "number": "0543236543", + "likes": ["Pizza", "Coding", "Brownie Points"] + }, + { + "firstName": "Harry", + "lastName": "Potter", + "number": "0994372684", + "likes": ["Hogwarts", "Magic", "Hagrid"] + }, + { + "firstName": "Sherlock", + "lastName": "Holmes", + "number": "0487345643", + "likes": ["Intriguing Cases", "Violin"] + }, + { + "firstName": "Kristian", + "lastName": "Vos", + "number": "unknown", + "likes": ["JavaScript", "Gaming", "Foxes"] + }, +]; + + +//Write your function in between these comments +function lookUpProfile(name, prop){ + for(var i in contacts){ + if(contacts[i].firstName === name) { + return contacts[i][prop] || "No such property"; + } + } + return "No such contact"; +} +//Write your function in between these comments + +lookUpProfile("Akira", "likes"); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/quoting-strings-with-single-quotes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/quoting-strings-with-single-quotes.spanish.md new file mode 100644 index 0000000000..65d89ab652 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/quoting-strings-with-single-quotes.spanish.md @@ -0,0 +1,73 @@ +--- +id: 56533eb9ac21ba0edf2244b4 +title: Quoting Strings with Single Quotes +localeTitle: Cotizando cuerdas con comillas simples +challengeType: 1 +--- + +## Description +
+Los valores de cadena en JavaScript se pueden escribir con comillas simples o dobles, siempre y cuando comience y termine con el mismo tipo de comillas. A diferencia de otros lenguajes de programación, las comillas simples y dobles funcionan de la misma manera en JavaScript. +
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
+La razón por la que podría querer usar un tipo de cita sobre la otra es si quiere usar ambos en una cadena. Esto puede suceder si desea guardar una conversación en una cadena y tener la conversación entre comillas. Otro uso sería guardar una etiqueta <a> con varios atributos entre comillas, todo dentro de una cadena. +
conversation = 'Finn exclaims to Jake, "Algebraic!"';
+Sin embargo, esto se convierte en un problema si necesita usar las citas más externas dentro de él. Recuerde, una cadena tiene el mismo tipo de cita al principio y al final. Pero si tiene la misma cita en algún punto intermedio, la cadena se detendrá antes y arrojará un error. +
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"'; // Throws an error
+En el goodStr anterior, puede usar ambas comillas de forma segura usando la barra invertida \ como un carácter de escape. +Nota
La barra invertida \ no debe confundirse con la barra inclinada / . No hacen lo mismo. +
+ +## Instructions +
+Cambie la cadena proporcionada por una cadena con comillas simples al principio y al final y sin caracteres de escape. +En este momento, la etiqueta <a> en la cadena usa comillas dobles en todas partes. Deberá cambiar las comillas externas a comillas simples para poder eliminar los caracteres de escape. +
+ +## Tests +
+ +```yml +tests: + - text: Eliminar todas las backslashes ( \ ) + testString: 'assert(!/\\/g.test(code) && myStr.match("\\s*\\s*Link\\s*\\s*"), "Remove all the backslashes (\)");' + - text: 'Debería tener dos comillas simples ' y cuatro comillas dobles " ' + testString: 'assert(code.match(/"/g).length === 4 && code.match(/"/g).length === 2, "You should have two single quotes ' and four double quotes "");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myStr = "Link"; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myStr = 'Link'; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.spanish.md new file mode 100644 index 0000000000..21aa64cf37 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.spanish.md @@ -0,0 +1,160 @@ +--- +id: 56533eb9ac21ba0edf2244cf +title: Record Collection +localeTitle: Colección de discos +challengeType: 1 +--- + +## Description +
+Se le asigna un objeto JSON que representa una parte de su colección de álbumes musicales. Cada álbum tiene varias propiedades y un número de identificación único como clave. No todos los álbumes tienen información completa. +Escriba una función que tome la id un álbum (como 2548 ), una propiedad prop (como "artist" o "tracks" ), y un value (como "Addicted to Love" ) para modificar los datos de esta colección. +Si la prop no es "tracks" y el value no está vacío ( "" ), actualice o establezca el value para la propiedad del álbum de grabación. +Su función debe devolver siempre el objeto de colección completo. +Existen varias reglas para manejar datos incompletos: +Si prop es "tracks" pero el álbum no tiene una propiedad de "tracks" , cree una matriz vacía antes de agregar el nuevo valor a la propiedad correspondiente del álbum. +Si prop es "tracks" y el value no está vacío ( "" ), presione el value sobre el final de la matriz de tracks existente del tracks . +Si el value está vacío ( "" ), elimine la propiedad de prop determinada del álbum. +Consejos
Utilice la bracket notation cuando acceda a las propiedades de objetos con variables . +Push es un método de matriz que puede leer sobre Mozilla Developer Network . +Puede volver a consultar Manipular objetos complejos Presentando la notación de objetos de JavaScript (JSON) para obtener una actualización. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: 'Después de updateRecords(5439, "artist", "ABBA") , el artist debe ser "ABBA" ' + testString: 'collection = collectionCopy; assert(updateRecords(5439, "artist", "ABBA")[5439]["artist"] === "ABBA", "After updateRecords(5439, "artist", "ABBA"), artist should be "ABBA"");' + - text: 'Después de updateRecords(5439, "tracks", "Take a Chance on Me") , los tracks deberían tener "Take a Chance on Me" como el último elemento.' + testString: 'assert(updateRecords(5439, "tracks", "Take a Chance on Me")[5439]["tracks"].pop() === "Take a Chance on Me", "After updateRecords(5439, "tracks", "Take a Chance on Me"), tracks should have "Take a Chance on Me" as the last element.");' + - text: 'Después de updateRecords(2548, "artist", "") , el artist no debe configurarse' + testString: 'updateRecords(2548, "artist", ""); assert(!collection[2548].hasOwnProperty("artist"), "After updateRecords(2548, "artist", ""), artist should not be set");' + - text: 'Después de updateRecords(1245, "tracks", "Addicted to Love") , las tracks deberían tener "Addicted to Love" como último elemento.' + testString: 'assert(updateRecords(1245, "tracks", "Addicted to Love")[1245]["tracks"].pop() === "Addicted to Love", "After updateRecords(1245, "tracks", "Addicted to Love"), tracks should have "Addicted to Love" as the last element.");' + - text: 'Después de updateRecords(2468, "tracks", "Free") , los tracks deberían tener "1999" como primer elemento.' + testString: 'assert(updateRecords(2468, "tracks", "Free")[2468]["tracks"][0] === "1999", "After updateRecords(2468, "tracks", "Free"), tracks should have "1999" as the first element.");' + - text: 'Después de updateRecords(2548, "tracks", "") , no se deben establecer tracks ' + testString: 'updateRecords(2548, "tracks", ""); assert(!collection[2548].hasOwnProperty("tracks"), "After updateRecords(2548, "tracks", ""), tracks should not be set");' + - text: 'Después de updateRecords(1245, "album", "Riptide") , el album debería ser "Riptide" ' + testString: 'assert(updateRecords(1245, "album", "Riptide")[1245]["album"] === "Riptide", "After updateRecords(1245, "album", "Riptide"), album should be "Riptide"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var collection = { + "2548": { + "album": "Slippery When Wet", + "artist": "Bon Jovi", + "tracks": [ + "Let It Rock", + "You Give Love a Bad Name" + ] + }, + "2468": { + "album": "1999", + "artist": "Prince", + "tracks": [ + "1999", + "Little Red Corvette" + ] + }, + "1245": { + "artist": "Robert Palmer", + "tracks": [ ] + }, + "5439": { + "album": "ABBA Gold" + } +}; +// Keep a copy of the collection for tests +var collectionCopy = JSON.parse(JSON.stringify(collection)); + +// Only change code below this line +function updateRecords(id, prop, value) { + + + return collection; +} + +// Alter values below to test your code +updateRecords(5439, "artist", "ABBA"); + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var collection = { + 2548: { + album: "Slippery When Wet", + artist: "Bon Jovi", + tracks: [ + "Let It Rock", + "You Give Love a Bad Name" + ] + }, + 2468: { + album: "1999", + artist: "Prince", + tracks: [ + "1999", + "Little Red Corvette" + ] + }, + 1245: { + artist: "Robert Palmer", + tracks: [ ] + }, + 5439: { + album: "ABBA Gold" + } +}; +// Keep a copy of the collection for tests +var collectionCopy = JSON.parse(JSON.stringify(collection)); + +// Only change code below this line +function updateRecords(id, prop, value) { + if(value === "") delete collection[id][prop]; + else if(prop === "tracks") { + collection[id][prop] = collection[id][prop] || []; + collection[id][prop].push(value); + } else { + collection[id][prop] = value; + } + + return collection; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.spanish.md new file mode 100644 index 0000000000..715605816e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/replacing-if-else-chains-with-switch.spanish.md @@ -0,0 +1,116 @@ +--- +id: 56533eb9ac21ba0edf2244e0 +title: Replacing If Else Chains with Switch +localeTitle: Reemplazo de cadenas de otro tipo con interruptor +challengeType: 1 +--- + +## Description +
+Si tiene muchas opciones para elegir, una instrucción switch puede ser más fácil de escribir que muchas instrucciones encadenadas if / else if . Lo siguiente: +
if (val === 1) {
  answer = "a";
} else if (val === 2) {
  answer = "b";
} else {
  answer = "c";
}
+puede ser reemplazado por: +
switch(val) {
  case 1:
    answer = "a";
    break;
  case 2:
    answer = "b";
    break;
  default:
    answer = "c";
}
+
+ +## Instructions +
+Cambie las sentencias if / else if encadenadas en una sentencia switch . +
+ +## Tests +
+ +```yml +tests: + - text: No debe utilizar ninguna else declaración en ningún lugar del editor. + testString: 'assert(!/else/g.test(code), "You should not use any else statements anywhere in the editor");' + - text: No debe utilizar ninguna sentencia if en ningún lugar del editor. + testString: 'assert(!/if/g.test(code), "You should not use any if statements anywhere in the editor");' + - text: Debe tener al menos cuatro declaraciones de break + testString: 'assert(code.match(/break/g).length >= 4, "You should have at least four break statements");' + - text: chainToSwitch("bob") debe ser "Marley" + testString: 'assert(chainToSwitch("bob") === "Marley", "chainToSwitch("bob") should be "Marley"");' + - text: chainToSwitch(42) debe ser "La Respuesta" + testString: 'assert(chainToSwitch(42) === "The Answer", "chainToSwitch(42) should be "The Answer"");' + - text: ' chainToSwitch(1) debe ser "No hay # 1"' + testString: 'assert(chainToSwitch(1) === "There is no #1", "chainToSwitch(1) should be "There is no #1"");' + - text: chainToSwitch(99) debería ser "¡Me chainToSwitch(99) por esto!" + testString: 'assert(chainToSwitch(99) === "Missed me by this much!", "chainToSwitch(99) should be "Missed me by this much!"");' + - text: chainToSwitch(7) debe ser "Ate Nine" + testString: 'assert(chainToSwitch(7) === "Ate Nine", "chainToSwitch(7) should be "Ate Nine"");' + - text: chainToSwitch("John") debe ser "" (cadena vacía) + testString: 'assert(chainToSwitch("John") === "", "chainToSwitch("John") should be "" (empty string)");' + - text: chainToSwitch(156) debe ser "" (cadena vacía) + testString: 'assert(chainToSwitch(156) === "", "chainToSwitch(156) should be "" (empty string)");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function chainToSwitch(val) { + var answer = ""; + // Only change code below this line + + if (val === "bob") { + answer = "Marley"; + } else if (val === 42) { + answer = "The Answer"; + } else if (val === 1) { + answer = "There is no #1"; + } else if (val === 99) { + answer = "Missed me by this much!"; + } else if (val === 7) { + answer = "Ate Nine"; + } + + // Only change code above this line + return answer; +} + +// Change this value to test +chainToSwitch(7); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function chainToSwitch(val) { + var answer = ""; + + switch(val) { + case "bob": + answer = "Marley"; + break; + case 42: + answer = "The Answer"; + break; + case 1: + answer = "There is no #1"; + break; + case 99: + answer = "Missed me by this much!"; + break; + case 7: + answer = "Ate Nine"; + } + return answer; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.spanish.md new file mode 100644 index 0000000000..7f27a63eeb --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-a-value-from-a-function-with-return.spanish.md @@ -0,0 +1,74 @@ +--- +id: 56533eb9ac21ba0edf2244c2 +title: Return a Value from a Function with Return +localeTitle: Devolver un valor de una función con retorno +challengeType: 1 +--- + +## Description +
+Podemos pasar valores a una función con argumentos . Puede usar una declaración de return para enviar un valor de vuelta de una función. +Ejemplo +
function plusThree(num) {
  return num + 3;
}
var answer = plusThree(5); // 8
+plusThree toma un argumento para num y devuelve un valor igual a num + 3 . +
+ +## Instructions +
+Cree una función timesFive que acepte un argumento, lo multiplique por 5 y devuelva el nuevo valor. Vea la última línea en el editor para ver un ejemplo de cómo puede probar su función timesFive . +
+ +## Tests +
+ +```yml +tests: + - text: timesFive debería ser una función + testString: 'assert(typeof timesFive === "function", "timesFive should be a function");' + - text: timesFive(5) debe devolver 25 + testString: 'assert(timesFive(5) === 25, "timesFive(5) should return 25");' + - text: timesFive(2) debe devolver 10 + testString: 'assert(timesFive(2) === 10, "timesFive(2) should return 10");' + - text: timesFive(0) debe devolver 0 + testString: 'assert(timesFive(0) === 0, "timesFive(0) should return 0");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +function minusSeven(num) { + return num - 7; +} + +// Only change code below this line + + + +console.log(minusSeven(10)); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function timesFive(num) { + return num * 5; +} +timesFive(10); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.spanish.md new file mode 100644 index 0000000000..beb2b0ead4 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/return-early-pattern-for-functions.spanish.md @@ -0,0 +1,84 @@ +--- +id: 56533eb9ac21ba0edf2244c4 +title: Return Early Pattern for Functions +localeTitle: Volver el patrón inicial para funciones +challengeType: 1 +--- + +## Description +
+Cuando se alcanza una declaración de return , la ejecución de la función actual se detiene y el control vuelve a la ubicación de la llamada. +Ejemplo +
function myFun() {
  console.log("Hello");
  return "World";
  console.log("byebye")
}
myFun();
+Lo anterior muestra "Hola" a la consola, devuelve "Mundo", pero "byebye" nunca se "byebye" , porque la función sale de la instrucción de return . +
+ +## Instructions +
+Modifique la función abTest para que si a o b sean menores que 0 la función saldrá inmediatamente con un valor undefined . +Pista
Recuerde que undefined es una palabra clave , no una cadena. +
+ +## Tests +
+ +```yml +tests: + - text: ' abTest(2,2) debe devolver un número' + testString: 'assert(typeof abTest(2,2) === "number" , "abTest(2,2) should return a number");' + - text: ' abTest(2,2) debe devolver 8 ' + testString: 'assert(abTest(2,2) === 8 , "abTest(2,2) should return 8");' + - text: ' abTest(-2,2) debe devolver undefined ' + testString: 'assert(abTest(-2,2) === undefined , "abTest(-2,2) should return undefined");' + - text: ' abTest(2,-2) debe devolver undefined ' + testString: 'assert(abTest(2,-2) === undefined , "abTest(2,-2) should return undefined");' + - text: ' abTest(2,8) debe devolver 18 ' + testString: 'assert(abTest(2,8) === 18 , "abTest(2,8) should return 18");' + - text: ' abTest(3,3) debe devolver 12 ' + testString: 'assert(abTest(3,3) === 12 , "abTest(3,3) should return 12");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function abTest(a, b) { + // Only change code below this line + + + + // Only change code above this line + + return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2)); +} + +// Change values below to test your code +abTest(2,2); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function abTest(a, b) { + if(a < 0 || b < 0) { + return undefined; + } + return Math.round(Math.pow(Math.sqrt(a) + Math.sqrt(b), 2)); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.spanish.md new file mode 100644 index 0000000000..e8ccde9b7e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions.spanish.md @@ -0,0 +1,73 @@ +--- +id: 5679ceb97cbaa8c51670a16b +title: Returning Boolean Values from Functions +localeTitle: Devolviendo valores booleanos desde funciones +challengeType: 1 +--- + +## Description +
+Puede recordar de la comparación con el operador de igualdad que todos los operadores de comparación devuelven un valor booleano true o false . +Algunas veces las personas usan una sentencia if / else para hacer una comparación, como esta: +
function isEqual(a,b) {
  if (a === b) {
    return true;
  } else {
    return false;
  }
}
+Pero hay una mejor manera de hacer esto. Como === devuelve true o false , podemos devolver el resultado de la comparación: +
function isEqual(a,b) {
  return a === b;
}
+
+ +## Instructions +
+Arreglar la función isLess permite eliminar las sentencias if/else . +
+ +## Tests +
+ +```yml +tests: + - text: ' isLess(10,15) debe devolver true ' + testString: 'assert(isLess(10,15) === true, "isLess(10,15) should return true");' + - text: ' isLess(15,10) debe devolver false ' + testString: 'assert(isLess(15, 10) === false, "isLess(15,10) should return false");' + - text: No debes usar ninguna declaración if o else + testString: 'assert(!/if|else/g.test(code), "You should not use any if or else statements");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function isLess(a, b) { + // Fix this code + if (a < b) { + return true; + } else { + return false; + } +} + +// Change these values to test +isLess(10, 15); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function isLess(a, b) { + return a < b; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.spanish.md new file mode 100644 index 0000000000..1a6f1c583a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements.spanish.md @@ -0,0 +1,96 @@ +--- +id: 56533eb9ac21ba0edf2244dd +title: Selecting from Many Options with Switch Statements +localeTitle: Selección de muchas opciones con instrucciones de cambio +challengeType: 1 +--- + +## Description +
+Si tiene muchas opciones para elegir, use una instrucción de switch . Una instrucción de switch prueba un valor y puede tener muchas declaraciones de case que definen varios valores posibles. Las declaraciones se ejecutan desde el primer valor de case coincidente hasta que se encuentra una break . +Aquí hay un ejemplo de pseudocódigo : +
switch(num) {
  case value1:
    statement1;
    break;
  case value2:
    statement2;
    break;
...
  case valueN:
    statementN;
    break;
}
+valores de +case se prueban con igualdad estricta ( === ). La break le dice a JavaScript que deje de ejecutar sentencias. Si se omite la break , se ejecutará la siguiente instrucción. +
+ +## Instructions +
+Escriba una instrucción de conmutación que pruebe val y establezca la answer para las siguientes condiciones:
1 - "alfa"
2 - "beta"
3 - "gamma"
4 - "delta" +
+ +## Tests +
+ +```yml +tests: + - text: caseInSwitch(1) debe tener un valor de "alfa" + testString: 'assert(caseInSwitch(1) === "alpha", "caseInSwitch(1) should have a value of "alpha"");' + - text: caseInSwitch(2) debe tener un valor de "beta" + testString: 'assert(caseInSwitch(2) === "beta", "caseInSwitch(2) should have a value of "beta"");' + - text: caseInSwitch(3) debe tener un valor de "gamma" + testString: 'assert(caseInSwitch(3) === "gamma", "caseInSwitch(3) should have a value of "gamma"");' + - text: caseInSwitch(4) debe tener un valor de "delta" + testString: 'assert(caseInSwitch(4) === "delta", "caseInSwitch(4) should have a value of "delta"");' + - text: No debes usar ninguna declaración if o else + testString: 'assert(!/else/g.test(code) || !/if/g.test(code), "You should not use any if or else statements");' + - text: Debe tener al menos 3 declaraciones de break + testString: 'assert(code.match(/break/g).length > 2, "You should have at least 3 break statements");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function caseInSwitch(val) { + var answer = ""; + // Only change code below this line + + + + // Only change code above this line + return answer; +} + +// Change this value to test +caseInSwitch(1); + +``` + +
+ + + +
+ +## Solution +
+ + +```js +function caseInSwitch(val) { + var answer = ""; + + switch(val) { + case 1: + answer = "alpha"; + break; + case 2: + answer = "beta"; + break; + case 3: + answer = "gamma"; + break; + case 4: + answer = "delta"; + } + return answer; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.spanish.md new file mode 100644 index 0000000000..187c597858 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/shopping-list.spanish.md @@ -0,0 +1,78 @@ +--- +id: 56533eb9ac21ba0edf2244bc +title: Shopping List +localeTitle: Lista de la compra +challengeType: 1 +--- + +## Description +
+Crea una lista de compras en la variable myList . La lista debe ser una matriz multidimensional que contenga varias subarreglas. +El primer elemento de cada sub-matriz debe contener una cadena con el nombre del elemento. El segundo elemento debe ser un número que represente la cantidad, es decir, +["Chocolate Bar", 15] +Debe haber al menos 5 subarreglos en la lista. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: myList debería ser una matriz + testString: 'assert(isArray, "myList should be an array");' + - text: Los primeros elementos de cada uno de sus subarreglos deben ser cadenas + testString: 'assert(hasString, "The first elements in each of your sub-arrays must all be strings");' + - text: Los segundos elementos en cada una de sus sub-matrices deben ser todos números + testString: 'assert(hasNumber, "The second elements in each of your sub-arrays must all be numbers");' + - text: Debes tener al menos 5 elementos en tu lista + testString: 'assert(count > 4, "You must have at least 5 items in your list");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var myList = []; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myList = [ + ["Candy", 10], + ["Potatoes", 12], + ["Eggs", 12], + ["Catfood", 1], + ["Toads", 9] +]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.spanish.md new file mode 100644 index 0000000000..9ec4118446 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/stand-in-line.spanish.md @@ -0,0 +1,116 @@ +--- +id: 56533eb9ac21ba0edf2244c6 +title: Stand in Line +localeTitle: Hacer cola +challengeType: 1 +--- + +## Description +
+En informática, una cola es una estructura de datos abstracta donde los elementos se mantienen en orden. Los nuevos elementos se pueden agregar al final de la queue y los elementos antiguos se quitan de la parte delantera de la queue . +Escriba una función nextInLine que tome una matriz ( arr ) y un número ( item ) como argumentos. +Agregue el número al final de la matriz, luego elimine el primer elemento de la matriz. +La función nextInLine debe devolver el elemento que se eliminó. +
+ +## Instructions +
+ +
+ +## Tests +
+ +```yml +tests: + - text: ' nextInLine([], 5) debe devolver un número'. + testString: 'assert.isNumber(nextInLine([],5), "nextInLine([], 5) should return a number.");' + - text: ' nextInLine([], 1) debe devolver 1 ' + testString: 'assert(nextInLine([],1) === 1, "nextInLine([], 1) should return 1");' + - text: ' nextInLine([2], 1) debe devolver 2 ' + testString: 'assert(nextInLine([2],1) === 2, "nextInLine([2], 1) should return 2");' + - text: ' nextInLine([5,6,7,8,9], 1) debe devolver 5 ' + testString: 'assert(nextInLine([5,6,7,8,9],1) === 5, "nextInLine([5,6,7,8,9], 1) should return 5");' + - text: 'Después de nextInLine(testArr, 10) , testArr[4] debería ser 10 ' + testString: 'nextInLine(testArr, 10); assert(testArr[4] === 10, "After nextInLine(testArr, 10), testArr[4] should be 10");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function nextInLine(arr, item) { + // Your code here + + return item; // Change this line +} + +// Test Setup +var testArr = [1,2,3,4,5]; + +// Display Code +console.log("Before: " + JSON.stringify(testArr)); +console.log(nextInLine(testArr, 6)); // Modify this line to test +console.log("After: " + JSON.stringify(testArr)); +``` + +
+ +### Before Test +
+ +```js +var logOutput = []; +var originalConsole = console +function capture() { + var nativeLog = console.log; + console.log = function (message) { + logOutput.push(message); + if(nativeLog.apply) { + nativeLog.apply(originalConsole, arguments); + } else { + var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); + nativeLog(nativeMsg); + } + }; +} + +function uncapture() { + console.log = originalConsole.log; +} + +capture(); +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var testArr = [ 1,2,3,4,5]; + +function nextInLine(arr, item) { + arr.push(item); + return arr.shift(); +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.spanish.md new file mode 100644 index 0000000000..91525286f5 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/store-multiple-values-in-one-variable-using-javascript-arrays.spanish.md @@ -0,0 +1,73 @@ +--- +id: bd7993c9c69feddfaeb8bdef +title: Store Multiple Values in one Variable using JavaScript Arrays +localeTitle: Almacene múltiples valores en una variable utilizando matrices de JavaScript +challengeType: 1 +--- + +## Description +
+Con las variables de array JavaScript, podemos almacenar varios datos en un solo lugar. +Inicia una declaración de matriz con un corchete de apertura, finalícelo con un corchete de cierre y ponga una coma entre cada entrada, como esto: +var sandwich = ["peanut butter", "jelly", "bread"] . +
+ +## Instructions +
+Modifique la nueva matriz myArray para que contenga tanto una string como un number (en ese orden). +Pista
Consulte el código de ejemplo en el editor de texto si se atasca. +
+ +## Tests +
+ +```yml +tests: + - text: myArray debería ser una array . + testString: 'assert(typeof myArray == "object", "myArray should be an array.");' + - text: El primer elemento en myArray debe ser una string . + testString: 'assert(typeof myArray[0] !== "undefined" && typeof myArray[0] == "string", "The first item in myArray should be a string.");' + - text: El segundo elemento en myArray debe ser un number . + testString: 'assert(typeof myArray[1] !== "undefined" && typeof myArray[1] == "number", "The second item in myArray should be a number.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourArray = ["John", 23]; + +// Only change code below this line. +var myArray = []; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myArray = ["The Answer", 42]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.spanish.md new file mode 100644 index 0000000000..fc10b7146c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator.spanish.md @@ -0,0 +1,94 @@ +--- +id: 56533eb9ac21ba0edf2244a8 +title: Storing Values with the Assignment Operator +localeTitle: Almacenamiento de valores con el operador de asignación +challengeType: 1 +--- + +## Description +
+En JavaScript, puede almacenar un valor en una variable con el operador de asignación . +myVariable = 5; +Esto asigna el valor Number 5 a myVariable . +asignación siempre va de derecha a izquierda. Todo a la derecha del operador = se resuelve antes de que el valor se asigne a la variable a la izquierda del operador. +
myVar = 5;
myNum = myVar;
+Esto asigna 5 a myVar y luego resuelve myVar a 5 nuevamente y lo asigna a myNum . +
+ +## Instructions +
+Asignar el valor 7 a la variable a . +Asigna los contenidos de a a la variable b . +
+ +## Tests +
+ +```yml +tests: + - text: No cambie el código por encima de la línea + testString: 'assert(/var a;/.test(code) && /var b = 2;/.test(code), "Do not change code above the line");' + - text: a debe tener un valor de 7 + testString: 'assert(typeof a === "number" && a === 7, "a should have a value of 7");' + - text: b debe tener un valor de 7 + testString: 'assert(typeof b === "number" && b === 7, "b should have a value of 7");' + - text: a debe asignarse a b con = + testString: 'assert(/b\s*=\s*a\s*;/g.test(code), "a should be assigned to b with =");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var a; +var b = 2; + +// Only change code below this line + +``` + +
+ +### Before Test +
+ +```js +if (typeof a != 'undefined') { + a = undefined; +} +if (typeof b != 'undefined') { + b = undefined; +} +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a; +var b = 2; +a = 7; +b = a; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.spanish.md new file mode 100644 index 0000000000..82b2ba2c92 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/subtract-one-number-from-another-with-javascript.spanish.md @@ -0,0 +1,70 @@ +--- +id: cf1111c1c11feddfaeb4bdef +title: Subtract One Number from Another with JavaScript +localeTitle: Resta un número de otro con JavaScript +challengeType: 1 +--- + +## Description +
+También podemos restar un número de otro. +JavaScript usa el símbolo - para restar. + +Ejemplo +
myVar = 12 - 6; // assigned 6
+ +
+ +## Instructions +
+Cambia el 0 por lo que la diferencia es 12 . +
+ +## Tests +
+ +```yml +tests: + - text: Haz la difference variable igual a 12. + testString: 'assert(difference === 12, "Make the variable difference equal 12.");' + - text: Sólo restar un número de 45. + testString: 'assert(/var\s*difference\s*=\s*45\s*-\s*[0-9]*;(?!\s*[a-zA-Z0-9]+)/.test(code),"Only subtract one number from 45.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +var difference = 45 - 0; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var difference = 45 - 33; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.spanish.md new file mode 100644 index 0000000000..e050221d20 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties.spanish.md @@ -0,0 +1,84 @@ +--- +id: 567af2437cbaa8c51670a16c +title: Testing Objects for Properties +localeTitle: Prueba de objetos para propiedades +challengeType: 1 +--- + +## Description +
+A veces es útil verificar si la propiedad de un objeto dado existe o no. Podemos usar el método de objetos .hasOwnProperty(propname) para determinar si ese objeto tiene el nombre de propiedad dado. .hasOwnProperty() devuelve true o false si se encuentra la propiedad o no. +Ejemplo +
var myObj = {
  top: "hat",
  bottom: "pants"
};
myObj.hasOwnProperty("top"); // true
myObj.hasOwnProperty("middle"); // false
+
+ +## Instructions +
+Modifique la función checkObj para probar myObj para checkProp . Si se encuentra la propiedad, devuelva el valor de esa propiedad. Si no, devuelve "Not Found" . +
+ +## Tests +
+ +```yml +tests: + - text: checkObj("gift") debe devolver "pony" . + testString: 'assert(checkObj("gift") === "pony", "checkObj("gift") should return "pony".");' + - text: checkObj("pet") debe devolver "kitten" . + testString: 'assert(checkObj("pet") === "kitten", "checkObj("pet") should return "kitten".");' + - text: checkObj("house") debe devolver "Not Found" . + testString: 'assert(checkObj("house") === "Not Found", "checkObj("house") should return "Not Found".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myObj = { + gift: "pony", + pet: "kitten", + bed: "sleigh" +}; + +function checkObj(checkProp) { + // Your Code Here + + return "Change Me!"; +} + +// Test your code by modifying these values +checkObj("gift"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +var myObj = { + gift: "pony", + pet: "kitten", + bed: "sleigh" +}; +function checkObj(checkProp) { + if(myObj.hasOwnProperty(checkProp)) { + return myObj[checkProp]; + } else { + return "Not Found"; + } +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.spanish.md new file mode 100644 index 0000000000..0418fe46d8 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability.spanish.md @@ -0,0 +1,75 @@ +--- +id: 56533eb9ac21ba0edf2244ba +title: Understand String Immutability +localeTitle: Entender la inmutabilidad de la cuerda +challengeType: 1 +--- + +## Description +
+En JavaScript, los valores de String son inmutables , lo que significa que no se pueden modificar una vez creados. +Por ejemplo, el siguiente código: +
var myStr = "Bob";
myStr[0] = "J";
+no puede cambiar el valor de myStr a "Trabajo", porque el contenido de myStr no se puede modificar. Tenga en cuenta que esto no significa que myStr no se pueda cambiar, solo que los caracteres individuales de un literal de cadena no se pueden cambiar. La única forma de cambiar myStr sería asignarlo con una nueva cadena, como esta: +
var myStr = "Bob";
myStr = "Job";
+
+ +## Instructions +
+Corrija la asignación a myStr para que contenga el valor de cadena de Hello World usando el enfoque que se muestra en el ejemplo anterior. +
+ +## Tests +
+ +```yml +tests: + - text: myStr debería tener un valor de Hello World + testString: 'assert(myStr === "Hello World", "myStr should have a value of Hello World");' + - text: No cambie el código por encima de la línea + testString: 'assert(/myStr = "Jello World"/.test(code), "Do not change the code above the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +var myStr = "Jello World"; + +// Only change code below this line + +myStr[0] = "H"; // Fix Me + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myStr = "Jello World"; +myStr = "Hello World"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.spanish.md new file mode 100644 index 0000000000..c4c294182b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-boolean-values.spanish.md @@ -0,0 +1,73 @@ +--- +id: bd7123c9c441eddfaeb5bdef +title: Understanding Boolean Values +localeTitle: Entendiendo los valores booleanos +challengeType: 1 +--- + +## Description +
+Otro tipo de datos es el booleano . Booleans solo pueden ser uno de dos valores: true o false . Básicamente son pequeños interruptores de encendido y apagado, donde true está "encendido" y false está "apagado". Estos dos estados son mutuamente excluyentes. +Nota
Boolean valores Boolean nunca se escriben entre comillas. Las strings "true" y "false" no son Boolean y no tienen un significado especial en JavaScript. +
+ +## Instructions +
+Modifique la función welcomeToBooleans para que devuelva true lugar de false cuando se haga clic en el botón Ejecutar. +
+ +## Tests +
+ +```yml +tests: + - text: 'La función welcomeToBooleans() debería devolver un valor booleano (verdadero / falso).' + testString: 'assert(typeof welcomeToBooleans() === "boolean", "The welcomeToBooleans() function should return a boolean (true/false) value.");' + - text: welcomeToBooleans() debe devolver true. + testString: 'assert(welcomeToBooleans() === true, "welcomeToBooleans() should return true.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function welcomeToBooleans() { + +// Only change code below this line. + +return false; // Change this line + +// Only change code above this line. +} +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function welcomeToBooleans() { + return true; // Change this line +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.spanish.md new file mode 100644 index 0000000000..9d3b301db0 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-case-sensitivity-in-variables.spanish.md @@ -0,0 +1,82 @@ +--- +id: 56533eb9ac21ba0edf2244ab +title: Understanding Case Sensitivity in Variables +localeTitle: Entender la sensibilidad de los casos en variables +challengeType: 1 +--- + +## Description +
+En JavaScript, todas las variables y nombres de funciones distinguen entre mayúsculas y minúsculas. Esto significa que la capitalización importa. +MYVAR no es lo mismo que MyVar ni myvar . Es posible tener múltiples variables distintas con el mismo nombre pero con una carcasa diferente. Se recomienda encarecidamente que, para mayor claridad, no utilice esta función de idioma. +

Mejores prácticas

+Escribe nombres de variables en JavaScript en camelCase . En camelCase , los nombres de variables de varias palabras tienen la primera palabra en minúsculas y la primera letra de cada palabra subsiguiente se escribe con mayúscula. +Ejemplos: +
var someVariable;
var anotherVariableName;
var thisVariableNameIsSoLong;
+
+ +## Instructions +
+Modifique las declaraciones y asignaciones existentes para que sus nombres utilicen camelCase .
No cree nuevas variables. +
+ +## Tests +
+ +```yml +tests: + - text: studlyCapVar está definido y tiene un valor de 10 + testString: 'assert(typeof studlyCapVar !== "undefined" && studlyCapVar === 10, "studlyCapVar is defined and has a value of 10");' + - text: properCamelCase está definido y tiene un valor de "A String" + testString: 'assert(typeof properCamelCase !== "undefined" && properCamelCase === "A String", "properCamelCase is defined and has a value of "A String"");' + - text: titleCaseOver está definido y tiene un valor de 9000 + testString: 'assert(typeof titleCaseOver !== "undefined" && titleCaseOver === 9000, "titleCaseOver is defined and has a value of 9000");' + - text: studlyCapVar debe usar camelCase en las secciones de declaración y asignación. + testString: 'assert(code.match(/studlyCapVar/g).length === 2, "studlyCapVar should use camelCase in both declaration and assignment sections.");' + - text: properCamelCase debe usar camelCase en las secciones de declaración y asignación. + testString: 'assert(code.match(/properCamelCase/g).length === 2, "properCamelCase should use camelCase in both declaration and assignment sections.");' + - text: titleCaseOver debe usar camelCase en las secciones de declaración y asignación. + testString: 'assert(code.match(/titleCaseOver/g).length === 2, "titleCaseOver should use camelCase in both declaration and assignment sections.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Declarations +var StUdLyCapVaR; +var properCamelCase; +var TitleCaseOver; + +// Assignments +STUDLYCAPVAR = 10; +PRoperCAmelCAse = "A String"; +tITLEcASEoVER = 9000; +``` + +
+ + + +
+ +## Solution +
+ + +```js +var studlyCapVar; +var properCamelCase; +var titleCaseOver; + +studlyCapVar = 10; +properCamelCase = "A String"; +titleCaseOver = 9000; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.spanish.md new file mode 100644 index 0000000000..6c6eb2faa3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-undefined-value-returned-from-a-function.spanish.md @@ -0,0 +1,83 @@ +--- +id: 598e8944f009e646fc236146 +title: Understanding Undefined Value returned from a Function +localeTitle: Entendiendo el valor indefinido devuelto por una función +challengeType: 1 +--- + +## Description +
+Una función puede incluir la declaración de return , pero no tiene que hacerlo. En el caso de que la función no tenga una declaración de return , cuando la llame, la función procesa el código interno pero el valor devuelto undefined está undefined . +Ejemplo +
var sum = 0;
function addSum(num) {
  sum = sum + num;
}
var returnedValue = addSum(3); // sum will be modified but returned value is undefined
+addSum es una función sin una declaración de return . La función cambiará la variable de sum global, pero el valor devuelto de la función es undefined +
+ +## Instructions +
+Crear una función addFive sin ningún argumento. Esta función agrega 5 a la variable de sum , pero su valor devuelto undefined está undefined . +
+ +## Tests +
+ +```yml +tests: + - text: addFive debería ser una función + testString: 'assert(typeof addFive === "function", "addFive should be a function");' + - text: sum debe ser igual a 8 + testString: 'assert(sum === 8, "sum should be equal to 8");' + - text: El valor devuelto de addFive debe estar undefined + testString: 'assert(addFive() === undefined, "Returned value from addFive should be undefined");' + - text: 'Dentro de tus funciones, suma 5 a la variable de sum ' + testString: 'assert(code.match(/(sum\s*\=\s*sum\s*\+\s*5)|(sum\s*\+\=\s*5)/g).length === 1, "Inside of your functions, add 5 to the sum variable");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var sum = 0; +function addThree() { + sum = sum + 3; +} + +// Only change code below this line + + + +// Only change code above this line +var returnedValue = addFive(); +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function addFive() { + sum = sum + 5; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.spanish.md new file mode 100644 index 0000000000..0e1caf0e88 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables.spanish.md @@ -0,0 +1,82 @@ +--- +id: 56533eb9ac21ba0edf2244aa +title: Understanding Uninitialized Variables +localeTitle: Entendiendo las variables sin inicializar +challengeType: 1 +--- + +## Description +
+Cuando se declaran las variables de JavaScript, tienen un valor inicial de undefined . Si realiza una operación matemática en una variable undefined , su resultado será NaN que significa "No es un número" . Si concatena una cadena con una variable undefined , obtendrá una cadena literal de "undefined" . +
+ +## Instructions +
+Inicialice las tres variables a , b y c con 5 , 10 y "I am a" respectivamente para que no queden undefined . +
+ +## Tests +
+ +```yml +tests: + - text: a debe definirse y evaluarse para tener el valor de 6 + testString: 'assert(typeof a === "number" && a === 6, "a should be defined and evaluated to have the value of 6");' + - text: b debe definirse y evaluarse para que tenga el valor de 15 + testString: 'assert(typeof b === "number" && b === 15, "b should be defined and evaluated to have the value of 15");' + - text: c no debe contener undefined y debe tener el valor "I am a String!" + testString: 'assert(!/undefined/.test(c) && c === "I am a String!", "c should not contain undefined and should have a value of "I am a String!"");' + - text: No cambie el código debajo de la línea + testString: 'assert(/a = a \+ 1;/.test(code) && /b = b \+ 5;/.test(code) && /c = c \+ " String!";/.test(code), "Do not change code below the line");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Initialize these three variables +var a; +var b; +var c; + +// Do not change code below this line + +a = a + 1; +b = b + 5; +c = c + " String!"; + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var a = 5; +var b = 10; +var c = "I am a"; +a = a + 1; +b = b + 5; +c = c + " String!"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.spanish.md new file mode 100644 index 0000000000..0ee9adbc36 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/updating-object-properties.spanish.md @@ -0,0 +1,95 @@ +--- +id: 56bbb991ad1ed5201cd392d1 +title: Updating Object Properties +localeTitle: Actualización de las propiedades del objeto +challengeType: 1 +--- + +## Description +
+Después de haber creado un objeto de JavaScript, puede actualizar sus propiedades en cualquier momento, como si fuera a actualizar cualquier otra variable. Puede utilizar la notación de puntos o corchetes para actualizar. +Por ejemplo, echemos un vistazo a ourDog : +
var ourDog = {
  "name": "Camper",
  "legs": 4,
  "tails": 1,
  "friends": ["everything!"]
};
+Ya que es un perro particularmente feliz, cambiemos su nombre a "Happy Camper". Así es como actualizamos la propiedad del nombre de su objeto: +ourDog.name = "Happy Camper"; o +ourDog["name"] = "Happy Camper"; +Ahora, cuando evaluamos ourDog.name , en lugar de obtener "Camper", obtendremos su nuevo nombre, "Happy Camper". +
+ +## Instructions +
+Actualizar la myDog del nombre del objeto myDog . Cambiemos su nombre de "Codificador" a "Codificador feliz". Puede utilizar la notación de puntos o corchetes. +
+ +## Tests +
+ +```yml +tests: + - text: Actualice la myDog "name" myDog para que sea igual a "Happy Coder". + testString: 'assert(/happy coder/gi.test(myDog.name), "Update myDog's "name" property to equal "Happy Coder".");' + - text: No edite la definición de myDog + testString: 'assert(/"name": "Coder"/.test(code), "Do not edit the myDog definition");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var ourDog = { + "name": "Camper", + "legs": 4, + "tails": 1, + "friends": ["everything!"] +}; + +ourDog.name = "Happy Camper"; + +// Setup +var myDog = { + "name": "Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"] +}; + +// Only change code below this line. + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var myDog = { + "name": "Coder", + "legs": 4, + "tails": 1, + "friends": ["freeCodeCamp Campers"] +}; +myDog.name = "Happy Coder"; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.spanish.md new file mode 100644 index 0000000000..38cab92da8 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-first-character-in-a-string.spanish.md @@ -0,0 +1,83 @@ +--- +id: bd7123c9c549eddfaeb5bdef +title: Use Bracket Notation to Find the First Character in a String +localeTitle: Usa la notación de corchete para encontrar el primer personaje en una cadena +challengeType: 1 +--- + +## Description +
+Bracket notation es una forma de obtener un carácter en un index específico dentro de una cadena. +La mayoría de los lenguajes de programación modernos, como JavaScript, no comienzan a contar en 1 como hacen los humanos. Comienzan en 0. Esto se conoce como indexación basada en cero . +Por ejemplo, el carácter en el índice 0 en la palabra "Charles" es "C". Entonces, si var firstName = "Charles" , puede obtener el valor de la primera letra de la cadena usando firstName[0] . +
+ +## Instructions +
+Use la notación de corchetes para encontrar el primer carácter en la variable lastName y asignarlo a firstLetterOfLastName . +Pista
Intenta mirar la declaración de la variable firstLetterOfFirstName si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: La variable firstLetterOfLastName debe tener el valor de L + testString: 'assert(firstLetterOfLastName === "L", "The firstLetterOfLastName variable should have the value of L.");' + - text: Usted debe utilizar la notación de soporte. + testString: 'assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/), "You should use bracket notation.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstLetterOfFirstName = ""; +var firstName = "Ada"; + +firstLetterOfFirstName = firstName[0]; + +// Setup +var firstLetterOfLastName = ""; +var lastName = "Lovelace"; + +// Only change code below this line +firstLetterOfLastName = lastName; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var firstLetterOfLastName = ""; +var lastName = "Lovelace"; + +// Only change code below this line +firstLetterOfLastName = lastName[0]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.spanish.md new file mode 100644 index 0000000000..4118668874 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-last-character-in-a-string.spanish.md @@ -0,0 +1,79 @@ +--- +id: bd7123c9c451eddfaeb5bdef +title: Use Bracket Notation to Find the Last Character in a String +localeTitle: Use la notación de corchete para encontrar el último carácter en una cadena +challengeType: 1 +--- + +## Description +
+Para obtener la última letra de una cadena, puedes restar una de la longitud de la cadena. +Por ejemplo, si var firstName = "Charles" , puede obtener el valor de la última letra de la cadena usando firstName[firstName.length - 1] . +
+ +## Instructions +
+Use la notación de corchetes para encontrar el último carácter en la variable lastName . +Pista
Intenta mirar la declaración de la variable lastLetterOfFirstName si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: lastLetterOfLastName debe ser "e". + testString: 'assert(lastLetterOfLastName === "e", "lastLetterOfLastName should be "e".");' + - text: Tienes que usar .length para obtener la última letra. + testString: 'assert(code.match(/\.length/g).length === 2, "You have to use .length to get the last letter.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstName = "Ada"; +var lastLetterOfFirstName = firstName[firstName.length - 1]; + +// Setup +var lastName = "Lovelace"; + +// Only change code below this line. +var lastLetterOfLastName = lastName; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var firstName = "Ada"; +var lastLetterOfFirstName = firstName[firstName.length - 1]; + +var lastName = "Lovelace"; +var lastLetterOfLastName = lastName[lastName.length - 1]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.spanish.md new file mode 100644 index 0000000000..bcb3b8612e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-character-in-a-string.spanish.md @@ -0,0 +1,76 @@ +--- +id: bd7123c9c450eddfaeb5bdef +title: Use Bracket Notation to Find the Nth Character in a String +localeTitle: Usa la notación de corchete para encontrar el enésimo carácter de una cadena +challengeType: 1 +--- + +## Description +
+También puede usar la notación de corchetes para obtener el carácter en otras posiciones dentro de una cadena. +Recuerde que las computadoras comienzan a contar en 0 , por lo que el primer carácter es en realidad el carácter cero. +
+ +## Instructions +
+Intentemos establecer thirdLetterOfLastName para que sea igual a la tercera letra de la variable lastName usando notación de corchete. +Pista
Intenta mirar la declaración de la variable secondLetterOfFirstName si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: La variable thirdLetterOfLastName debe tener el valor de v . + testString: 'assert(thirdLetterOfLastName === "v", "The thirdLetterOfLastName variable should have the value of v.");' + - text: Usted debe utilizar la notación de soporte. + testString: 'assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/), "You should use bracket notation.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstName = "Ada"; +var secondLetterOfFirstName = firstName[1]; + +// Setup +var lastName = "Lovelace"; + +// Only change code below this line. +var thirdLetterOfLastName = lastName; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var lastName = "Lovelace"; +var thirdLetterOfLastName = lastName[2]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.spanish.md new file mode 100644 index 0000000000..56565bd430 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-bracket-notation-to-find-the-nth-to-last-character-in-a-string.spanish.md @@ -0,0 +1,79 @@ +--- +id: bd7123c9c452eddfaeb5bdef +title: Use Bracket Notation to Find the Nth-to-Last Character in a String +localeTitle: Use la notación de corchete para encontrar el carácter Nth-to-Last en una cadena +challengeType: 1 +--- + +## Description +
+Puede usar el mismo principio que acabamos de usar para recuperar el último carácter de una cadena para recuperar el enésimo al último carácter. +Por ejemplo, puede obtener el valor de la tercera a la última letra de la cadena var firstName = "Charles" usando firstName[firstName.length - 3] +
+ +## Instructions +
+Use la notación de corchetes para encontrar el segundo hasta el último carácter en la cadena lastName . +Pista
Intenta mirar la declaración de la variable thirdToLastLetterOfFirstName si te quedas atascado. +
+ +## Tests +
+ +```yml +tests: + - text: secondToLastLetterOfLastName debe ser "c". + testString: 'assert(secondToLastLetterOfLastName === "c", "secondToLastLetterOfLastName should be "c".");' + - text: Tienes que usar .length para obtener la segunda última letra. + testString: 'assert(code.match(/\.length/g).length === 2, "You have to use .length to get the second last letter.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +var firstName = "Ada"; +var thirdToLastLetterOfFirstName = firstName[firstName.length - 3]; + +// Setup +var lastName = "Lovelace"; + +// Only change code below this line +var secondToLastLetterOfLastName = lastName; + + +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +var firstName = "Ada"; +var thirdToLastLetterOfFirstName = firstName[firstName.length - 3]; + +var lastName = "Lovelace"; +var secondToLastLetterOfLastName = lastName[lastName.length - 2]; +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.spanish.md new file mode 100644 index 0000000000..296fdd3ecc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements.spanish.md @@ -0,0 +1,92 @@ +--- +id: cf1111c1c12feddfaeb3bdef +title: Use Conditional Logic with If Statements +localeTitle: Usa lógica condicional con sentencias if +challengeType: 1 +--- + +## Description +
+If se usan sentencias para tomar decisiones en código. La palabra clave if le dice a JavaScript que ejecute el código entre llaves en ciertas condiciones, definidas entre paréntesis. Estas condiciones se conocen como condiciones Boolean y solo pueden ser true o false . +Cuando la condición se evalúa como true , el programa ejecuta la instrucción dentro de las llaves. Cuando la condición booleana se evalúa como false , la instrucción dentro de las llaves no se ejecutará. +pseudocódigo +
if ( condition is true ) {
   statement is executed
}
+Ejemplo +
function test (myCondition) {
  if (myCondition) {
     return "It was true";
  }
  return "It was false";
}
test(true); // returns "It was true"
test(false); // returns "It was false"
+Cuando se llama a la test con un valor true , la sentencia if evalúa myCondition para ver si es true o no. Dado que es true , la función devuelve "It was true" . Cuando llamamos a test con un valor de false , myCondition no es true y la instrucción entre llaves no se ejecuta y la función devuelve "It was false" . +
+ +## Instructions +
+Cree una instrucción if dentro de la función para devolver "Yes, that was true" si el parámetro wasThatTrue es true y devuelva "No, that was false" contrario. +
+ +## Tests +
+ +```yml +tests: + - text: trueOrFalse debe ser una función + testString: 'assert(typeof trueOrFalse === "function", "trueOrFalse should be a function");' + - text: trueOrFalse(true) debe devolver una cadena + testString: 'assert(typeof trueOrFalse(true) === "string", "trueOrFalse(true) should return a string");' + - text: trueOrFalse(false) debe devolver una cadena + testString: 'assert(typeof trueOrFalse(false) === "string", "trueOrFalse(false) should return a string");' + - text: ' trueOrFalse(true) debe devolver "Sí, eso fue cierto"' + testString: 'assert(trueOrFalse(true) === "Yes, that was true", "trueOrFalse(true) should return "Yes, that was true"");' + - text: ' trueOrFalse(false) debe devolver "No, eso fue falso"' + testString: 'assert(trueOrFalse(false) === "No, that was false", "trueOrFalse(false) should return "No, that was false"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +function ourTrueOrFalse(isItTrue) { + if (isItTrue) { + return "Yes, it's true"; + } + return "No, it's false"; +} + +// Setup +function trueOrFalse(wasThatTrue) { + + // Only change code below this line. + + + + // Only change code above this line. + +} + +// Change this value to test +trueOrFalse(true); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function trueOrFalse(wasThatTrue) { + if (wasThatTrue) { + return "Yes, that was true"; + } + return "No, that was false"; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.spanish.md new file mode 100644 index 0000000000..0bf5a8c265 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-multiple-conditional-ternary-operators.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7b7e367417b2b2512b21 +title: Use Multiple Conditional (Ternary) Operators +localeTitle: Usar múltiples operadores condicionales (ternarios) +challengeType: 1 +--- + +## Description +
+En el desafío anterior, usaste un solo conditional operator . También puede encadenarlos para verificar múltiples condiciones. +La siguiente función usa las declaraciones if, else if, y else para verificar múltiples condiciones: +
function findGreaterOrEqual(a, b) {
  if(a === b) {
    return "a and b are equal";
  }
  else if(a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}
+La función anterior puede reescribirse utilizando múltiples conditional operators : +
function findGreaterOrEqual(a, b) {
  return (a === b) ? "a and b are equal" : (a > b) ? "a is greater" : "b is greater";
}
+
+ +## Instructions +
+Use múltiples conditional operators en la función checkSign para verificar si un número es positivo, negativo o cero. +
+ +## Tests +
+ +```yml +tests: + - text: checkSign debe usar múltiples conditional operators + testString: 'assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code), "checkSign should use multiple conditional operators");' + - text: checkSign(10) debe devolver "positivo". Tenga en cuenta que la capitalización importa + testString: 'assert(checkSign(10) === "positive", "checkSign(10) should return "positive". Note that capitalization matters");' + - text: checkSign(-12) debe devolver "negativo". Tenga en cuenta que la capitalización importa + testString: 'assert(checkSign(-12) === "negative", "checkSign(-12) should return "negative". Note that capitalization matters");' + - text: checkSign(0) debe devolver "cero". Tenga en cuenta que la capitalización importa + testString: 'assert(checkSign(0) === "zero", "checkSign(0) should return "zero". Note that capitalization matters");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function checkSign(num) { + +} + +checkSign(10); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.spanish.md new file mode 100644 index 0000000000..bdc91a1cb9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-conditional-ternary-operator.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d7b7e367417b2b2512b24 +title: Use the Conditional (Ternary) Operator +localeTitle: Usar el Operador Condicional (Ternario) +challengeType: 1 +--- + +## Description +
+El operador condicional , también llamado operador ternario , se puede usar como una expresión de una línea si-else. +La sintaxis es: +condition ? statement-if-true : statement-if-false; +La siguiente función utiliza una instrucción if-else para verificar una condición: +
function findGreater(a, b) {
  if(a > b) {
    return "a is greater";
  }
  else {
    return "b is greater";
  }
}
+Esto se puede reescribir usando el conditional operator : +
function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater";
}
+
+ +## Instructions +
+Use el conditional operator en la función checkEqual para verificar si dos números son iguales o no. La función debe devolver verdadero o falso. +
+ +## Tests +
+ +```yml +tests: + - text: checkEqual debe usar el conditional operator + testString: 'assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code), "checkEqual should use the conditional operator");' + - text: ' checkEqual(1, 2) debe devolver falso' + testString: 'assert(checkEqual(1, 2) === false, "checkEqual(1, 2) should return false");' + - text: ' checkEqual(1, 1) debe devolver verdadero' + testString: 'assert(checkEqual(1, 1) === true, "checkEqual(1, 1) should return true");' + - text: ' checkEqual(1, -1) debe devolver falso' + testString: 'assert(checkEqual(1, -1) === false, "checkEqual(1, -1) should return false");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function checkEqual(a, b) { + +} + +checkEqual(1, 2); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.spanish.md new file mode 100644 index 0000000000..4a0e2a35bf --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function-with-a-radix.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7b7e367417b2b2512b22 +title: Use the parseInt Function with a Radix +localeTitle: Usa la función parseInt con un Radix +challengeType: 1 +--- + +## Description +
+La parseInt() analiza una cadena y devuelve un entero. Toma un segundo argumento para el radix, que especifica la base del número en la cadena. El radix puede ser un número entero entre 2 y 36. +La función call se parece a: +parseInt(string, radix); +Y aquí hay un ejemplo: +var a = parseInt("11", 2); +La variable radix dice que "11" está en el sistema binario, o base 2. Este ejemplo convierte la cadena "11" en un entero 3. +
+ +## Instructions +
+Use parseInt() en la función convertToInteger para que convierta un número binario en un entero y lo devuelva. +
+ +## Tests +
+ +```yml +tests: + - text: convertToInteger debe usar la parseInt() + testString: 'assert(/parseInt/g.test(code), "convertToInteger should use the parseInt() function");' + - text: convertToInteger("10011") debe devolver un número + testString: 'assert(typeof(convertToInteger("10011")) === "number", "convertToInteger("10011") should return a number");' + - text: convertToInteger("10011") debe devolver 19 + testString: 'assert(convertToInteger("10011") === 19, "convertToInteger("10011") should return 19");' + - text: convertToInteger("111001") debe devolver 57 + testString: 'assert(convertToInteger("111001") === 57, "convertToInteger("111001") should return 57");' + - text: convertToInteger("JamesBond") debe devolver NaN + testString: 'assert.isNaN(convertToInteger("JamesBond"), "convertToInteger("JamesBond") should return NaN");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function convertToInteger(str) { + +} + +convertToInteger("10011"); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.spanish.md new file mode 100644 index 0000000000..e3882a523d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/use-the-parseint-function.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7b7e367417b2b2512b23 +title: Use the parseInt Function +localeTitle: Usa la función de parseInt +challengeType: 1 +--- + +## Description +
+La parseInt() analiza una cadena y devuelve un entero. Aquí hay un ejemplo: +var a = parseInt("007"); +La función anterior convierte la cadena "007" en un número entero 7. Si el primer carácter de la cadena no se puede convertir en un número, devuelve NaN . +
+ +## Instructions +
+Use parseInt() en la función convertToInteger para que convierta la cadena de entrada str en un entero, y la devuelva. +
+ +## Tests +
+ +```yml +tests: + - text: convertToInteger debe usar la parseInt() + testString: 'assert(/parseInt/g.test(code), "convertToInteger should use the parseInt() function");' + - text: convertToInteger("56") debe devolver un número + testString: 'assert(typeof(convertToInteger("56")) === "number", "convertToInteger("56") should return a number");' + - text: convertToInteger("56") debe devolver 56 + testString: 'assert(convertToInteger("56") === 56, "convertToInteger("56") should return 56");' + - text: convertToInteger("77") debe devolver 77 + testString: 'assert(convertToInteger("77") === 77, "convertToInteger("77") should return 77");' + - text: convertToInteger("JamesBond") debe devolver NaN + testString: 'assert.isNaN(convertToInteger("JamesBond"), "convertToInteger("JamesBond") should return NaN");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function convertToInteger(str) { + +} + +convertToInteger("56"); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.spanish.md new file mode 100644 index 0000000000..a7f4462824 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups.spanish.md @@ -0,0 +1,116 @@ +--- +id: 56533eb9ac21ba0edf2244ca +title: Using Objects for Lookups +localeTitle: Uso de objetos para búsquedas +challengeType: 1 +--- + +## Description +
+objetos pueden considerarse como un almacenamiento de clave / valor, como un diccionario. Si tiene datos tabulares, puede usar un objeto para "buscar" valores en lugar de una instrucción switch o una cadena if/else . Esto es más útil cuando sabe que sus datos de entrada están limitados a un cierto rango. +Aquí hay un ejemplo de una búsqueda de alfabeto inversa simple: +
var alpha = {
  1:"Z",
  2:"Y",
  3:"X",
  4:"W",
  ...
  24:"C",
  25:"B",
  26:"A"
};
alpha[2]; // "Y"
alpha[24]; // "C"

var value = 2;
alpha[value]; // "Y"
+
+ +## Instructions +
+Convertir la instrucción switch en un objeto llamado lookup . Úselo para buscar val y asignar la cadena asociada a la variable de result . +
+ +## Tests +
+ +```yml +tests: + - text: phoneticLookup("alpha") debería ser igual a "Adams" + testString: 'assert(phoneticLookup("alpha") === "Adams", "phoneticLookup("alpha") should equal "Adams"");' + - text: phoneticLookup("bravo") debería ser igual a "Boston" + testString: 'assert(phoneticLookup("bravo") === "Boston", "phoneticLookup("bravo") should equal "Boston"");' + - text: phoneticLookup("charlie") debe ser igual a "Chicago" + testString: 'assert(phoneticLookup("charlie") === "Chicago", "phoneticLookup("charlie") should equal "Chicago"");' + - text: phoneticLookup("delta") debe ser igual a "Denver" + testString: 'assert(phoneticLookup("delta") === "Denver", "phoneticLookup("delta") should equal "Denver"");' + - text: phoneticLookup("echo") debe ser igual a "Easy" + testString: 'assert(phoneticLookup("echo") === "Easy", "phoneticLookup("echo") should equal "Easy"");' + - text: phoneticLookup("foxtrot") debe ser igual a "Frank" + testString: 'assert(phoneticLookup("foxtrot") === "Frank", "phoneticLookup("foxtrot") should equal "Frank"");' + - text: phoneticLookup("") debe ser igual a undefined + testString: 'assert(typeof phoneticLookup("") === "undefined", "phoneticLookup("") should equal undefined");' + - text: No debes modificar la declaración de return . + testString: 'assert(code.match(/return\sresult;/), "You should not modify the return statement");' + - text: 'No debe usar case , switch , o if declaraciones' + testString: 'assert(!/case|switch|if/g.test(code.replace(/([/]{2}.*)|([/][*][^/*]*[*][/])/g,"")), "You should not use case, switch, or if statements"); ' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Setup +function phoneticLookup(val) { + var result = ""; + + // Only change code below this line + switch(val) { + case "alpha": + result = "Adams"; + break; + case "bravo": + result = "Boston"; + break; + case "charlie": + result = "Chicago"; + break; + case "delta": + result = "Denver"; + break; + case "echo": + result = "Easy"; + break; + case "foxtrot": + result = "Frank"; + } + + // Only change code above this line + return result; +} + +// Change this value to test +phoneticLookup("charlie"); +``` + +
+ + + +
+ +## Solution +
+ + +```js +function phoneticLookup(val) { + var result = ""; + + var lookup = { + alpha: "Adams", + bravo: "Boston", + charlie: "Chicago", + delta: "Denver", + echo: "Easy", + foxtrot: "Frank" + }; + + result = lookup[val]; + + return result; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.spanish.md new file mode 100644 index 0000000000..a8695fd955 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/word-blanks.spanish.md @@ -0,0 +1,86 @@ +--- +id: 56533eb9ac21ba0edf2244bb +title: Word Blanks +localeTitle: Palabras en blanco +challengeType: 1 +--- + +## Description +
+Ahora usaremos nuestro conocimiento de cuerdas para construir un juego de palabras al estilo de " Mad Libs " que llamamos "Word Blanks". Creará una oración estilo "Rellene los espacios en blanco" (opcionalmente humorística). +En un juego de "Mad Libs", se te proporcionan frases con algunas palabras faltantes, como sustantivos, verbos, adjetivos y adverbios. Luego, completa las piezas faltantes con las palabras que elijas de manera que la oración completa tenga sentido. +Considere esta oración: "Fue realmente ____ , y nosotros ____ nosotros ____ ". Esta oración tiene tres partes faltantes: un adjetivo, un verbo y un adverbio, y podemos agregar palabras de nuestra elección para completarla. Luego podemos asignar la oración completa a una variable de la siguiente manera: +
var sentence = "It was really" + "hot" + ", and we" + "laughed" + "ourselves" + "silly.";
+
+ +## Instructions +
+En este desafío, le proporcionamos un sustantivo, un verbo, un adjetivo y un adverbio. Debe formar una oración completa con las palabras de su elección, junto con las palabras que proporcionamos. +Necesitará utilizar el operador de concatenación de cadenas + para crear una nueva cadena, utilizando las variables proporcionadas: myNoun , myAdjective , myVerb y myAdverb . A continuación, asignará la cadena formada a la variable de result . +También deberá tener en cuenta los espacios en su cadena, de modo que la oración final tenga espacios entre todas las palabras. El resultado debe ser una oración completa. +
+ +## Tests +
+ +```yml +tests: + - text: ' wordBlanks("","","","") debe devolver una cadena.' + testString: 'assert(typeof wordBlanks("","","","") === "string", "wordBlanks("","","","") should return a string.");' + - text: ' wordBlanks("dog", "big", "ran", "quickly") debe contener todas las palabras pasadas separadas por caracteres que no sean de palabras (y cualquier palabra adicional en su libreta). + testString: 'assert(/\bdog\b/.test(test1) && /\bbig\b/.test(test1) && /\bran\b/.test(test1) && /\bquickly\b/.test(test1),"wordBlanks("dog", "big", "ran", "quickly") should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).");' + - text: ' wordBlanks("cat", "little", "hit", "slowly") debe contener todas las palabras pasadas separadas por caracteres que no sean de palabras (y cualquier otra palabra adicional en su madlib). + testString: 'assert(/\bcat\b/.test(test2) && /\blittle\b/.test(test2) && /\bhit\b/.test(test2) && /\bslowly\b/.test(test2),"wordBlanks("cat", "little", "hit", "slowly") should contain all of the passed in words separated by non-word characters (and any additional words in your madlib).");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) { + // Your code below this line + var result = ""; + + // Your code above this line + return result; +} + +// Change the words here to test your function +wordBlanks("dog", "big", "ran", "quickly"); +``` + +
+ + +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function wordBlanks(myNoun, myAdjective, myVerb, myAdverb) { + var result = ""; + + result = "Once there was a " + myNoun + " which was very " + myAdjective + ". "; + result += "It " + myVerb + " " + myAdverb + " around the yard."; + + return result; +} +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.spanish.md new file mode 100644 index 0000000000..ee89f3d975 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/basic-javascript/write-reusable-javascript-with-functions.spanish.md @@ -0,0 +1,108 @@ +--- +id: 56bbb991ad1ed5201cd392cf +title: Write Reusable JavaScript with Functions +localeTitle: Escribir JavaScript reutilizable con funciones +challengeType: 1 +--- + +## Description +
+En JavaScript, podemos dividir nuestro código en partes reutilizables llamadas funciones . +Aquí hay un ejemplo de una función: +
function functionName() {
  console.log("Hello World");
}
+Puede llamar o invocar esta función usando su nombre seguido de paréntesis, como este: +functionName(); +Cada vez que se llame a la función, se imprimirá el mensaje "Hello World" en la consola dev. Todo el código entre las llaves se ejecutará cada vez que se llame a la función. +
+ +## Instructions +
+
  1. Crea una función llamada reusableFunction que imprime "Hi World" en la consola dev.
  2. Llama a la función.
+
+ +## Tests +
+ +```yml +tests: + - text: reusableFunction debería ser una función + testString: 'assert(typeof reusableFunction === "function", "reusableFunction should be a function");' + - text: reusableFunction debería dar salida a "Hi World" a la consola dev + testString: 'assert("Hi World" === logOutput, "reusableFunction should output "Hi World" to the dev console");' + - text: Llame a reusableFunction después de definirlo + testString: 'assert(/^\s*reusableFunction\(\)\s*;/m.test(code), "Call reusableFunction after you define it");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Example +function ourReusableFunction() { + console.log("Heyya, World"); +} + +ourReusableFunction(); + +// Only change code below this line + +``` + +
+ +### Before Test +
+ +```js +var logOutput = ""; +var originalConsole = console +function capture() { + var nativeLog = console.log; + console.log = function (message) { + if(message && message.trim) logOutput = message.trim(); + if(nativeLog.apply) { + nativeLog.apply(originalConsole, arguments); + } else { + var nativeMsg = Array.prototype.slice.apply(arguments).join(' '); + nativeLog(nativeMsg); + } + }; +} + +function uncapture() { + console.log = originalConsole.log; +} + +capture(); +``` + +
+ +### After Test +
+ +```js +console.info('after the test'); +``` + +
+ +
+ +## Solution +
+ + +```js +function reusableFunction() { + console.log("Hi World"); +} +reusableFunction(); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function.spanish.md new file mode 100644 index 0000000000..61b4448ccf --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-arguments-passed-in-the-wrong-order-when-calling-a-function.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d7b85367417b2b2512b3a +title: Catch Arguments Passed in the Wrong Order When Calling a Function +localeTitle: Detectar argumentos pasados ​​en el orden incorrecto al llamar a una función +challengeType: 1 +--- + +## Description +
+Continuando con la discusión sobre las funciones de llamada, el siguiente error a tener en cuenta es cuando los argumentos de una función se suministran en el orden incorrecto. Si los argumentos son de tipos diferentes, como una función que espera una matriz y un entero, es probable que se produzca un error de tiempo de ejecución. Si los argumentos son del mismo tipo (todos los enteros, por ejemplo), entonces la lógica del código no tendrá sentido. Asegúrese de proporcionar todos los argumentos necesarios, en el orden correcto para evitar estos problemas. +
+ +## Instructions +
+La función raiseToPower eleva una base a un exponente. Desafortunadamente, no se llama correctamente: repare el código para que el valor de la power sea ​​el esperado 8. +
+ +## Tests +
+ +```yml +tests: + - text: 'Su código debería fijar la power variable de modo que sea igual a 2 elevado a la tercera potencia, no 3 elevado a la segunda potencia'. + testString: 'assert(power == 8, "Your code should fix the variable power so it equals 2 raised to the 3rd power, not 3 raised to the 2nd power.");' + - text: Su código debe usar el orden correcto de los argumentos para la raiseToPower función raiseToPower . + testString: 'assert(code.match(/raiseToPower\(\s*?base\s*?,\s*?exp\s*?\);/g), "Your code should use the correct order of the arguments for the raiseToPower function call.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function raiseToPower(b, e) { + return Math.pow(b, e); +} + +let base = 2; +let exp = 3; +let power = raiseToPower(exp, base); +console.log(power); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.spanish.md new file mode 100644 index 0000000000..21c4697fd9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-missing-open-and-closing-parenthesis-after-a-function-call.spanish.md @@ -0,0 +1,62 @@ +--- +id: 587d7b85367417b2b2512b39 +title: Catch Missing Open and Closing Parenthesis After a Function Call +localeTitle: Atrapa los paréntesis abiertos y de cierre que faltan después de una llamada de función +challengeType: 1 +--- + +## Description +
+Cuando una función o método no acepta ningún argumento, puede olvidarse de incluir los paréntesis de apertura y cierre (vacíos) al llamarla. Muchas veces, el resultado de una llamada de función se guarda en una variable para otro uso en su código. Este error se puede detectar registrando valores de variables (o sus tipos) en la consola y al ver que uno se establece en una referencia de función, en lugar del valor esperado que devuelve la función. +Las variables en el siguiente ejemplo son diferentes: +
function myFunction() {
  return "You rock!";
}
let varOne = myFunction; // set to equal a function
let varTwo = myFunction(); // set to equal the string "You rock!"
+
+ +## Instructions +
+Corrija el código para que el result variable se establezca en el valor devuelto al llamar a la función getNine . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe arreglar el result variable para que se establezca en el número que devuelve la función getNine . + testString: 'assert(result == 9, "Your code should fix the variable result so it is set to the number that the function getNine returns.");' + - text: Su código debe llamar a la función getNine . + testString: 'assert(code.match(/getNine\(\)/g).length == 2, "Your code should call the getNine function.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function getNine() { + let x = 6; + let y = 3; + return x + y; +} + +let result = getNine; +console.log(result); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names.spanish.md new file mode 100644 index 0000000000..c684577d5d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-misspelled-variable-and-function-names.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7b84367417b2b2512b35 +title: Catch Misspelled Variable and Function Names +localeTitle: Capturar nombres de funciones y variables mal escritas +challengeType: 1 +--- + +## Description +
+console.log() y los métodos de typeof son las dos formas principales de verificar los valores intermedios y los tipos de salida del programa. Ahora es el momento de entrar en las formas comunes que toman los errores. Un problema de nivel de sintaxis con el que los usuarios rápidos pueden compadecerse es el humilde error de ortografía. +transpuestos, faltantes o mal colocados en una variable o nombre de función harán que el navegador busque un objeto que no existe, y se quejen en forma de un error de referencia. Las variables de JavaScript y los nombres de funciones distinguen entre mayúsculas y minúsculas. +
+ +## Instructions +
+Corrija los dos errores de ortografía en el código para que netWorkingCapital cálculo de netWorkingCapital . +
+ +## Tests +
+ +```yml +tests: + - text: 'Verifique la ortografía de las dos variables utilizadas en el cálculo de netWorkingCapital, la salida de la consola debe mostrar que "El capital de trabajo neto es: 2". + testString: 'assert(netWorkingCapital === 2, "Check the spelling of the two variables used in the netWorkingCapital calculation, the console output should show that "Net working capital is: 2".");' + - text: No debe haber instancias de variables mal escritas en el código. + testString: 'assert(!code.match(/recievables/g), "There should be no instances of mis-spelled variables in the code.");' + - text: La variable cuentas por cobrar debe declararse y usarse correctamente en el código. + testString: 'assert(code.match(/receivables/g).length == 2, "The receivables variable should be declared and used properly in the code.");' + - text: No debe haber instancias de variables mal escritas en el código. + testString: 'assert(!code.match(/payable;/g), "There should be no instances of mis-spelled variables in the code.");' + - text: La variable payables debe declararse y usarse correctamente en el código. + testString: 'assert(code.match(/payables/g).length == 2, "The payables variable should be declared and used properly in the code.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let receivables = 10; +let payables = 8; +let netWorkingCapital = recievables - payable; +console.log(`Net working capital is: ${netWorkingCapital}`); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.spanish.md new file mode 100644 index 0000000000..8325a91bce --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-mixed-usage-of-single-and-double-quotes.spanish.md @@ -0,0 +1,59 @@ +--- +id: 587d7b84367417b2b2512b37 +title: Catch Mixed Usage of Single and Double Quotes +localeTitle: Uso mixto de capturas de comillas simples y dobles +challengeType: 1 +--- + +## Description +
+JavaScript permite el uso de comillas simples (") y dobles (" ") para declarar una cadena. Decidir cuál usar generalmente se reduce a preferencias personales, con algunas excepciones. +Tener dos opciones es excelente cuando una cadena tiene contracciones u otro fragmento de texto entre comillas. Solo tenga cuidado de no cerrar la cadena demasiado pronto, lo que provoca un error de sintaxis. +Aquí hay algunos ejemplos de comillas de mezcla: +
// These are correct:
const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";
// This is incorrect:
const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
+Por supuesto, está bien usar solo un estilo de citas. Puede escapar de las comillas dentro de la cadena usando el carácter de escape de barra invertida (\): +
// Correct use of same quotes:
const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
+
+ +## Instructions +
+Arregle la cadena para que use comillas diferentes para el valor href , o escape de las existentes. Mantenga las comillas dobles alrededor de toda la cadena. +
+ +## Tests +
+ +```yml +tests: + - text: 'Tu código debe corregir las comillas alrededor del valor href "#Home", ya sea cambiándolos o escapándolos.' + testString: 'assert(code.match(//g), "Your code should fix the quotes around the href value "#Home" by either changing or escaping them.");' + - text: Su código debe mantener las comillas dobles alrededor de toda la cadena. + testString: 'assert(code.match(/"

.*?<\/p>";/g), "Your code should keep the double quotes around the entire string.");' + +``` + +

+ +## Challenge Seed +
+ +
+ +```js +let innerHtml = "

Click here to return home

"; +console.log(innerHtml); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.spanish.md new file mode 100644 index 0000000000..f595df0838 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-off-by-one-errors-when-using-indexing.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b86367417b2b2512b3b +title: Catch Off By One Errors When Using Indexing +localeTitle: Descubrir por uno errores al utilizar la indexación +challengeType: 1 +--- + +## Description +
+Off by one errors (a veces llamado OBOE) se recortan cuando intentas apuntar a un índice específico de una cadena o matriz (para dividir o acceder a un segmento), o cuando se recorren los índices de ellos. La indexación de JavaScript comienza en cero, no en uno, lo que significa que el último índice siempre es uno menos que la longitud del elemento. Si intenta acceder a un índice igual a la longitud, el programa puede arrojar un error de referencia de "índice fuera de rango" o imprimir undefined . +Cuando usa métodos de cadena o matriz que toman rangos de índice como argumentos, es útil leer la documentación y comprender si son inclusivos (el elemento en el índice dado es parte de lo que se devuelve) o no. Aquí hay algunos ejemplos de errores off por uno: +
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let len = alphabet.length;
for (let i = 0; i <= len; i++) {
  // loops one too many times at the end
  console.log(alphabet[i]);
}
for (let j = 1; j < len; j++) {
  // loops one too few times and misses the first character at index 0
  console.log(alphabet[j]);
}
for (let k = 0; k < len; k++) {
  // Goldilocks approves - this is just right
  console.log(alphabet[k]);
}
+
+ +## Instructions +
+Corrija los dos errores de indexación en la siguiente función para que todos los números del 1 al 5 se impriman en la consola. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la condición inicial del bucle para que comience en el primer índice. + testString: 'assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1, "Your code should set the initial condition of the loop so it starts at the first index.");' + - text: Su código debe arreglar la condición inicial del bucle para que el índice comience en 0. + testString: 'assert(!code.match(/i\s?=\s*?1\s*?;/g), "Your code should fix the initial condition of the loop so that the index starts at 0.");' + - text: Su código debe establecer la condición de terminal del bucle para que se detenga en el último índice. + testString: 'assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1, "Your code should set the terminal condition of the loop so it stops at the last index.");' + - text: Su código debe fijar la condición de terminal del bucle para que se detenga en 1 antes de la longitud. + testString: 'assert(!code.match(/i\s*?<=\s*?len;/g), "Your code should fix the terminal condition of the loop so that it stops at 1 before the length.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function countToFive() { + let firstFive = "12345"; + let len = firstFive.length; + // Fix the line below + for (let i = 1; i <= len; i++) { + // Do not alter code below this line + console.log(firstFive[i]); + } +} + +countToFive(); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.spanish.md new file mode 100644 index 0000000000..d354515544 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-unclosed-parentheses-brackets-braces-and-quotes.spanish.md @@ -0,0 +1,56 @@ +--- +id: 587d7b84367417b2b2512b36 +title: 'Catch Unclosed Parentheses, Brackets, Braces and Quotes' +localeTitle: 'Captura paréntesis, corchetes, llaves y citas' +challengeType: 1 +--- + +## Description +
+Otro error de sintaxis a tener en cuenta es que todos los paréntesis de apertura, paréntesis, llaves y comillas tienen un par de cierre. El olvido de una pieza suele suceder cuando edita el código existente e inserta elementos con uno de los tipos de pares. Además, tenga cuidado al anidar bloques de código en otros, como agregar una función de devolución de llamada como un argumento a un método. +Una forma de evitar este error es tan pronto como se escribe el carácter de apertura, incluya inmediatamente la coincidencia de cierre, luego mueva el cursor entre ellos y continúe la codificación. Afortunadamente, la mayoría de los editores de código modernos generan la segunda mitad del par automáticamente. +
+ +## Instructions +
+Arreglar los errores de dos pares en el código. +
+ +## Tests +
+ +```yml +tests: + - text: Tu código debería arreglar la pieza faltante de la matriz. + testString: 'assert(code.match(/myArray\s*?=\s*?\[\s*?1\s*?,\s*?2\s*?,\s*?3\s*?\];/g), "Your code should fix the missing piece of the array.");' + - text: 'Su código debe arreglar la pieza faltante del método . Reduce () . La salida de la consola debería mostrar que "la suma de los valores de la matriz es: 6". + testString: 'assert(arraySum === 6, "Your code should fix the missing piece of the .reduce() method. The console output should show that "Sum of array values is: 6".");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let myArray = [1, 2, 3; +let arraySum = myArray.reduce((previous, current => previous + current); +console.log(`Sum of array values is: ${arraySum}`); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.spanish.md new file mode 100644 index 0000000000..03514d680c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/catch-use-of-assignment-operator-instead-of-equality-operator.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d7b85367417b2b2512b38 +title: Catch Use of Assignment Operator Instead of Equality Operator +localeTitle: Captura el uso del operador de asignación en lugar del operador de igualdad +challengeType: 1 +--- + +## Description +
+Los programas de derivación, es decir, los que hacen cosas diferentes si se cumplen ciertas condiciones, dependen de las declaraciones if , else if , y else en JavaScript. La condición a veces toma la forma de probar si un resultado es igual a un valor. +Esta lógica se habla (en inglés, al menos) como "si x es igual a y, entonces ..." que puede traducirse literalmente en código usando el operador = , o asignación. Esto conduce a un flujo de control inesperado en su programa. +Como se cubrió en desafíos anteriores, el operador de asignación ( = ) en JavaScript asigna un valor a un nombre de variable. Y los operadores == y === verifican la igualdad (las pruebas triples === para la igualdad estricta, lo que significa que tanto el valor como el tipo son iguales). +El siguiente código asigna x para ser 2, que se evalúa como true . Casi todos los valores en JavaScript se evalúan como true , excepto lo que se conoce como valores "falsos": false , 0 , "" (una cadena vacía), NaN , undefined y null . +
let x = 1;
let y = 2;
if (x = y) {
  // this code block will run for any value of y (unless y were originally set as a falsy)
} else {
  // this code block is what should run (but won't) in this example
}
+
+ +## Instructions +
+Corrija la condición para que el programa ejecute la rama derecha y se asigne el valor apropiado al result . +
+ +## Tests +
+ +```yml +tests: + - text: 'Tu código debería arreglar la condición para que verifique la igualdad, en lugar de usar la asignación'. + testString: 'assert(result == "Not equal!", "Your code should fix the condition so it checks for equality, instead of using assignment.");' + - text: La condición puede usar == o === para probar la igualdad. + testString: 'assert(code.match(/x\s*?===?\s*?y/g), "The condition can use either == or === to test for equality.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let x = 7; +let y = 9; +let result = "to come"; + +if(x = y) { + result = "Equal!"; +} else { + result = "Not equal!"; +} + +console.log(result); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.spanish.md new file mode 100644 index 0000000000..eab13b4fec --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/prevent-infinite-loops-with-a-valid-terminal-condition.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d7b86367417b2b2512b3d +title: Prevent Infinite Loops with a Valid Terminal Condition +localeTitle: Prevenga los bucles infinitos con una condición de terminal válida +challengeType: 1 +--- + +## Description +
+El tema final es el bucle infinito temido. Los bucles son excelentes herramientas cuando necesita que su programa ejecute un bloque de código un cierto número de veces o hasta que se cumpla una condición, pero necesitan una condición de terminal que termine el bucle. Es probable que los bucles infinitos congelen o bloqueen el navegador, y causen un caos general en la ejecución del programa, que nadie quiere. +No fue un ejemplo de un bucle infinito en la introducción a esta sección - que no tenía condición terminal para salir de la while bucle interior loopy() . ¡NO llames a esta función! +
function loopy() {
  while(true) {
    console.log("Hello, world!");
  }
}
+El trabajo del programador es asegurarse de que finalmente se alcance la condición del terminal, que le indica al programa cuándo salir del código de bucle. Un error es aumentar o disminuir una variable de contador en la dirección incorrecta de la condición del terminal. Otro es restablecer accidentalmente un contador o variable de índice dentro del código de bucle, en lugar de incrementarlo o disminuirlo. +
+ +## Instructions +
+El myFunc() función contiene un bucle infinito debido a que la condición terminal i != 4 Nunca será evaluada como false (y romper el bucle) - i aumentará en 2 de cada pasada, y saltar a la derecha durante 4 desde i es impar para empezar. Corrija el operador de comparación en la condición de terminal para que el bucle solo se ejecute para i menor o igual a 4. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe cambiar el operador de comparación en la condición del terminal (la parte media) del bucle for . + testString: 'assert(code.match(/i\s*?<=\s*?4;/g).length == 1, "Your code should change the comparison operator in the terminal condition (the middle part) of the for loop.");' + - text: Su código debe arreglar el operador de comparación en la condición terminal del bucle. + testString: 'assert(!code.match(/i\s*?!=\s*?4;/g), "Your code should fix the comparison operator in the terminal condition of the loop.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function myFunc() { + for (let i = 1; i != 4; i += 2) { + console.log("Still going!"); + } +} +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.spanish.md new file mode 100644 index 0000000000..147099e8ae --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/understanding-the-differences-between-the-freecodecamp-and-browser-console.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d7b83367417b2b2512b37 +title: Understanding the Differences between the freeCodeCamp and Browser Console +localeTitle: Comprender las diferencias entre freeCodeCamp y Browser Console +challengeType: 1 +--- + +## Description +
+Es posible que haya notado que algunos desafíos de JavaScript de freeCodeCamp incluyen su propia consola. Esta consola se comporta de forma un poco diferente a la consola del navegador que usó en el último desafío. +El siguiente desafío pretende resaltar algunas de las diferencias entre la consola freeCodeCamp y la consola del navegador. +Primero, la consola del navegador. Cuando cargue y ejecute un archivo JavaScript normal en su navegador, las declaraciones de console.log() imprimirán exactamente lo que usted les dice que impriman en la consola del navegador la cantidad exacta de veces que solicitó. En su editor de texto en el navegador, el proceso es ligeramente diferente y puede ser confuso al principio. +valores pasados ​​a console.log() en el bloque del editor de texto ejecutan cada conjunto de pruebas, así como una vez más para cualquier llamada de función que tenga en su código. +Esto se presta a un comportamiento interesante y puede hacer que se tropiece con usted al principio, porque un valor registrado que espera ver solo una vez puede imprimirse muchas más, dependiendo de la cantidad de pruebas y los valores que se pasan a esas pruebas. +Si desea ver solo su salida única y no tiene que preocuparse por ejecutar los ciclos de prueba, puede usar console.clear() . +
+ +## Instructions +
+Use console.log() para imprimir las variables en el código donde se indica. + +
+ +## Tests +
+ +```yml +tests: + - text: Use console.log() para imprimir la variable outputTwo . En la consola del navegador, esto debería imprimir el valor de la variable dos veces. + testString: 'assert(code.match(/console\.log\(outputTwo\)/g), "Use console.log() to print the outputTwo variable. In your Browser Console this should print out the value of the variable two times.");' + - text: Utilice console.log() para imprimir la variable outputOne . + testString: 'assert(code.match(/console\.log\(outputOne\)/g), "Use console.log() to print the outputOne variable.");' + - text: Use console.clear() para modificar su salida de modo que la variable outputOne solo outputOne una vez. + testString: 'assert(code.match(/^(\s*console.clear\(\);?\s*)$/gm), "Use console.clear() to modify your output so that outputOne variable only outputs once.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +// Open your browser console +let outputTwo = "This will print to the browser console 2 times"; +// Use console.log() to print the outputTwo variable + + +let outputOne = "Try to get this to log only once to the browser console"; +// Use console.clear() in the next line to print the outputOne only once + + +// Use console.log() to print the outputOne variable + + +``` + +
+ + + +
+ +## Solution +
+ + +```js +let outputTwo = "This will print to the browser console 2 times"; console.log(outputTwo); let outputOne = "Try to get this to log only once to the browser console"; +console.clear(); +console.log(outputOne); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.spanish.md new file mode 100644 index 0000000000..ff8207d37b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-caution-when-reinitializing-variables-inside-a-loop.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d7b86367417b2b2512b3c +title: Use Caution When Reinitializing Variables Inside a Loop +localeTitle: Tenga cuidado al reinicializar variables dentro de un bucle +challengeType: 1 +--- + +## Description +
+A veces es necesario guardar información, incrementar los contadores o restablecer las variables dentro de un bucle. Un problema potencial es cuando las variables deben reinicializarse y no, o viceversa. Esto es particularmente peligroso si restablece accidentalmente la variable que se está utilizando para la condición del terminal, causando un bucle infinito. +impresión de valores de variables con cada ciclo de su ciclo utilizando console.log() puede descubrir un comportamiento defectuoso relacionado con el restablecimiento, o no restablecer una variable. +
+ +## Instructions +
+Se supone que la siguiente función crea una matriz bidimensional con m filas n columnas de ceros. Desafortunadamente, no está produciendo el resultado esperado porque la variable de row no se está reinicializando (configurada de nuevo en una matriz vacía) en el bucle externo. Corrija el código para que devuelva una matriz correcta de 3x2 de ceros, que se parece a [[0, 0], [0, 0], [0, 0]] . +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe establecer la variable de matrix en una matriz que contenga 3 filas de 2 columnas de ceros cada una. + testString: 'assert(JSON.stringify(matrix) == "[[0,0],[0,0],[0,0]]", "Your code should set the matrix variable to an array holding 3 rows of 2 columns of zeroes each.");' + - text: La variable matrix debe tener 3 filas. + testString: 'assert(matrix.length == 3, "The matrix variable should have 3 rows.");' + - text: La variable matrix debe tener 2 columnas en cada fila. + testString: 'assert(matrix[0].length == 2 && matrix[1].length === 2 && matrix[2].length === 2, "The matrix variable should have 2 columns in each row.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function zeroArray(m, n) { + // Creates a 2-D array with m rows and n columns of zeroes + let newArray = []; + let row = []; + for (let i = 0; i < m; i++) { + // Adds the m-th row into newArray + + for (let j = 0; j < n; j++) { + // Pushes n zeroes into the current row to create the columns + row.push(0); + } + // Pushes the current row, which now has n zeroes in it, to the array + newArray.push(row); + } + return newArray; +} + +let matrix = zeroArray(3, 2); +console.log(matrix); +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.spanish.md new file mode 100644 index 0000000000..4be92b9805 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-the-javascript-console-to-check-the-value-of-a-variable.spanish.md @@ -0,0 +1,64 @@ +--- +id: 587d7b83367417b2b2512b33 +title: Use the JavaScript Console to Check the Value of a Variable +localeTitle: Use la consola de JavaScript para verificar el valor de una variable +challengeType: 1 +--- + +## Description +
+Tanto Chrome como Firefox tienen excelentes consolas de JavaScript, también conocidas como DevTools, para depurar su JavaScript. +Puede encontrar Herramientas de desarrollador en el menú de Chrome o la Consola web en el menú de FireFox. Si está utilizando un navegador diferente o un teléfono móvil, le recomendamos que cambie a la computadora de escritorio Firefox o Chrome. +El método console.log() , que "imprime" la salida de lo que está entre sus paréntesis en la consola, probablemente sea la herramienta de depuración más útil. Colocarlo en puntos estratégicos en su código puede mostrarle los valores intermedios de las variables. Es una buena práctica tener una idea de lo que debería ser la salida antes de ver qué es. Tener puntos de control para ver el estado de sus cálculos a lo largo de su código ayudará a reducir dónde está el problema. +Aquí hay un ejemplo para imprimir '¡Hola mundo!' a la consola: +console.log('Hello world!'); +
+ +## Instructions +
+Use el método console.log() para imprimir el valor de la variable a donde se indica en el código. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe usar console.log() para verificar el valor de la variable a . + testString: 'assert(code.match(/console\.log\(a\)/g), "Your code should use console.log() to check the value of the variable a.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let a = 5; +let b = 1; +a++; +// Add your code below this line + + +let sumAB = a + b; +console.log(sumAB); +``` + +
+ + + +
+ +## Solution +
+ + +```js +var a = 5; console.log(a); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.spanish.md new file mode 100644 index 0000000000..c28a60fd30 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/debugging/use-typeof-to-check-the-type-of-a-variable.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7b84367417b2b2512b34 +title: Use typeof to Check the Type of a Variable +localeTitle: Utilice typeof para comprobar el tipo de una variable +challengeType: 1 +--- + +## Description +
+Puede usar typeof para verificar la estructura de datos, o tipo, de una variable. Esto es útil en la depuración cuando se trabaja con múltiples tipos de datos. Si crees que estás agregando dos números, pero uno es en realidad una cadena, los resultados pueden ser inesperados. Los errores de tipo pueden estar al acecho en cálculos o llamadas de función. Tenga cuidado especialmente cuando esté accediendo y trabajando con datos externos en forma de un objeto de notación de objetos de JavaScript (JSON). +Aquí hay algunos ejemplos usando typeof : +
console.log(typeof ""); // outputs "string"
console.log(typeof 0); // outputs "number"
console.log(typeof []); // outputs "object"
console.log(typeof {}); // outputs "object"
+JavaScript reconoce seis tipos de datos primitivos (inmutables): Boolean , Null , no Undefined , Number , String y Symbol (nuevo con ES6) y un tipo para elementos mutables: Object . Tenga en cuenta que en JavaScript, las matrices son técnicamente un tipo de objeto. +
+ +## Instructions +
+Añadir dos console.log() declaraciones para comprobar el typeof cada una de las dos variables de seven y three en el código. +
+ +## Tests +
+ +```yml +tests: + - text: Su código debe usar typeof en dos sentencias console.log() para verificar el tipo de las variables. + testString: 'assert(code.match(/console\.log\(typeof[\( ].*\)?\)/g).length == 2, "Your code should use typeof in two console.log() statements to check the type of the variables.");' + - text: Su código debe usar typeof para verificar el tipo de la variable seven . + testString: 'assert(code.match(/typeof[\( ]seven\)?/g), "Your code should use typeof to check the type of the variable seven.");' + - text: Su código debe usar typeof para verificar el tipo de la variable three . + testString: 'assert(code.match(/typeof[\( ]three\)?/g), "Your code should use typeof to check the type of the variable three.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +let seven = 7; +let three = "3"; +console.log(seven + three); +// Add your code below this line + +``` + +
+ + + +
+ +## Solution +
+ + +```js +let seven = 7;let three = "3";console.log(typeof seven); +console.log(typeof three); +``` + +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.spanish.md new file mode 100644 index 0000000000..66b6fec2ea --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/compare-scopes-of-the-var-and-let-keywords.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7b87367417b2b2512b40 +title: Compare Scopes of the var and let Keywords +localeTitle: Comparar los alcances de la var y dejar Palabras clave +challengeType: 1 +--- + +## Description +
+Cuando declara una variable con la palabra clave var , se declara globalmente o localmente si se declara dentro de una función. +La palabra clave let comporta de manera similar, pero con algunas características adicionales. Cuando declara una variable con la palabra clave let dentro de un bloque, una declaración o una expresión, su alcance se limita a ese bloque, declaración o expresión. +Por ejemplo: +
var numArray = [];
for (var i = 0; i < 3; i++) {
  numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
+Con el var de palabras clave, i se declara a nivel mundial. Entonces, cuando se ejecuta i++ , se actualiza la variable global. Este código es similar al siguiente: +
var numArray = [];
var i;
for (i = 0; i < 3; i++) {
  numArray.push(i);
}
console.log(numArray);
// returns [0, 1, 2]
console.log(i);
// returns 3
+Este comportamiento causará problemas si tuviera que crear una función y almacenarla para su uso posterior dentro de un bucle for que usa la variable i . Esto se debe a que la función almacenada siempre se referirá al valor de la variable global actualizada i . +
var printNumTwo;
for (var i = 0; i < 3; i++) {
  if(i === 2){
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 3
+Como se puede ver, printNumTwo() imprime 3 y no 2. Esto se debe a que el valor asignado a i se actualiza y el printNumTwo() devuelve el mundial i y no el valor i tenía cuando la función fue creada en el bucle. La palabra clave let no sigue este comportamiento: +
'use strict';
let printNumTwo;
for (let i = 0; i < 3; i++) {
  if (i === 2) {
    printNumTwo = function() {
      return i;
    };
  }
}
console.log(printNumTwo());
// returns 2
console.log(i);
// returns "i is not defined"
+i no está definido porque no se declaró en el ámbito global. Solo se declara dentro de la sentencia for loop. printNumTwo() devolvió el valor correcto porque se crearon tres variables i diferentes con valores únicos (0, 1 y 2) mediante la palabra clave let dentro de la instrucción de bucle. +
+ +## Instructions +
+Fijar el código para que i declarado en la sentencia if es una variable independiente que i declaré en la primera línea de la función. Asegúrese de no utilizar la palabra clave var en ningún lugar de su código. +Este ejercicio está diseñado para ilustrar la diferencia entre cómo var y let palabras clave asignen un alcance a la variable declarada. Cuando se programa una función similar a la utilizada en este ejercicio, a menudo es mejor usar diferentes nombres de variables para evitar confusiones. +
+ +## Tests +
+ +```yml +tests: + - text: var no existe en el código. + testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"var does not exist in code.");' + - text: La variable i declaradas en la sentencia if debe ser igual a "ámbito de bloque". + testString: 'getUserInput => assert(getUserInput("index").match(/(i\s*=\s*).*\s*.*\s*.*\1("|")block\s*scope\2/g), "The variable i declared in the if statement should equal "block scope".");' + - text: checkScope() debería devolver "alcance de función" + testString: 'assert(checkScope() === "function scope", "checkScope() should return "function scope"");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +function checkScope() { +"use strict"; + var i = "function scope"; + if (true) { + i = "block scope"; + console.log("Block scope i is: ", i); + } + console.log("Function scope i is: ", i); + return i; +} +``` + +
+ + + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.spanish.md new file mode 100644 index 0000000000..4422c328ae --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-an-export-fallback-with-export-default.spanish.md @@ -0,0 +1,64 @@ +--- +id: 587d7b8c367417b2b2512b58 +title: Create an Export Fallback with export default +localeTitle: Crear un respaldo de exportación con la exportación predeterminada +challengeType: 1 +--- + +## Description +
+En la lección de export , aprendió sobre la sintaxis denominada exportación con nombre . Esto le permitió tener múltiples funciones y variables disponibles para usar en otros archivos. +Hay otra sintaxis de export que necesita conocer, conocida como exportación predeterminada . Por lo general, utilizará esta sintaxis si solo se exporta un valor desde un archivo. También se utiliza para crear un valor de reserva para un archivo o módulo. +Aquí hay un ejemplo rápido de la export default : +
export default function add(x,y) {
  return x + y;
}
+Nota: Dado que export default se utiliza para declarar un valor de reserva para un módulo o archivo, solo puede tener un valor como exportación predeterminada en cada módulo o archivo. Además, no puede usar export default con var , let o const +
+ +## Instructions +
+La siguiente función debe ser el valor de retorno para el módulo. Por favor agregue el código necesario para hacerlo. +
+ +## Tests +
+ +```yml +tests: + - text: Uso adecuado de la export reserva. + testString: 'getUserInput => assert(getUserInput("index").match(/export\s+default\s+function\s+subtract\(x,y\)\s+{return\s+x\s-\s+y;}/g), "Proper used of export fallback.");' + +``` + +
+ +## Challenge Seed +
+ +
+ +```js +"use strict"; +function subtract(x,y) {return x - y;} +``` + +
+ +### Before Test +
+ +```js +window.exports = function(){}; +``` + +
+ + +
+ +## Solution +
+ +```js +// solution required +``` +
diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.spanish.md new file mode 100644 index 0000000000..879dde3b31 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/create-strings-using-template-literals.spanish.md @@ -0,0 +1,83 @@ +--- +id: 587d7b8a367417b2b2512b4e +title: Create Strings using Template Literals +localeTitle: Crear cadenas usando literales de plantilla +challengeType: 1 +--- + +## Description +
+Una nueva característica de ES6 es la plantilla literal . Este es un tipo especial de cadena que facilita la creación de cadenas complejas. +Los literales de plantilla le permiten crear cadenas de varias líneas y usar las funciones de interpolación de cadenas para crear cadenas. +Considera el siguiente código: +
const person = {
  name: "Zodiac Hasbro",
  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.
+Muchas cosas pasaron allí. +En primer lugar, el ejemplo utiliza comillas ( ` ), no comillas ( ' o " ), para envolver la cadena. +En segundo lugar, observe que la cadena es multilínea, tanto en el código como en la salida. Esto ahorra la inserción de \n en +La sintaxis ${variable} utilizada anteriormente es un marcador de posición. Básicamente, no tendrá que usar más la concatenación con el operador + . Para agregar variables a las cadenas, simplemente suelte la variable en una cadena de plantilla y la envuelva con ${ y } . De forma similar, puede incluir otras expresiones en su cadena literal, por ejemplo, ${a + b} . +Esta nueva forma de crear cadenas le brinda más flexibilidad para crear cadenas sólidas. +
+ +## Instructions +
+Use la sintaxis literal de la plantilla con comillas invertidas para mostrar cada entrada de la matriz de failure del objeto de result . Cada entrada debe incluirse dentro de un elemento li con el atributo de clase text-warning , y debe aparecer dentro de resultDisplayArray . +
+ +## Tests +
+ +```yml +tests: + - text: resultDisplayArray es una matriz que contiene mensajes de result failure . + testString: 'assert(typeof makeList(result.failure) === "object" && resultDisplayArray.length === 3, "resultDisplayArray is a list containing result failure messages.");' + - text: resultDisplayArray es el resultado deseado. + testString: 'assert(makeList(result.failure).every((v, i) => v === `
  • ${result.failure[i]}
  • ` || v === `
  • ${result.failure[i]}
  • `), "resultDisplayArray is the desired output.");' + - text: Se utilizaron cadenas de plantilla. + testString: 'getUserInput => assert(getUserInput("index").match(/`.*`/g), "Template strings were not used");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const result = { + success: ["max-length", "no-amd", "prefer-arrow-functions"], + failure: ["no-var", "var-on-top", "linebreak"], + skipped: ["id-blacklist", "no-dup-keys"] +}; +function makeList(arr) { + "use strict"; + + // change code below this line + const resultDisplayArray = null; + // change code above this line + + return resultDisplayArray; +} +/** + * makeList(result.failure) should return: + * [ `
  • no-var
  • `, + * `
  • var-on-top
  • `, + * `
  • linebreak
  • ` ] + **/ +const resultDisplayArray = makeList(result.failure); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.spanish.md new file mode 100644 index 0000000000..df812677a7 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/declare-a-read-only-variable-with-the-const-keyword.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7b87367417b2b2512b41 +title: Declare a Read-Only Variable with the const Keyword +localeTitle: Declare una variable de solo lectura con la palabra clave const +challengeType: 1 +--- + +## Description +
    +let no es la única forma nueva de declarar variables. En ES6, también puede declarar variables usando la palabra clave const . +const tiene todas las características increíbles que let tener, con la ventaja adicional de que las variables declaradas con const son de solo lectura. Son un valor constante, lo que significa que una vez que una variable se asigna con const , no se puede reasignar. +
    "use strict"
    const FAV_PET = "Cats";
    FAV_PET = "Dogs"; // returns error
    +Como puede ver, al intentar reasignar una variable declarada con const generará un error. Siempre debe nombrar variables que no desee reasignar utilizando la palabra clave const . Esto ayuda cuando intenta accidentalmente reasignar una variable que está destinada a permanecer constante. Una práctica común al nombrar constantes es usar todas las letras en mayúsculas, con palabras separadas por un guión bajo. +
    + +## Instructions +
    +Cambie el código para que todas las variables se declaren usando let o const . Use let cuando quiera que la variable cambie, y const cuando quiera que la variable permanezca constante. Además, cambie el nombre de las variables declaradas con const para que se ajusten a las prácticas comunes, es decir, las constantes deben estar en mayúsculas. +
    + +## Tests +
    + +```yml +tests: + - text: var no existe en su código. + testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"var does not exist in your code.");' + - text: SENTENCE debe ser una variable constante declarada con const . + testString: 'getUserInput => assert(getUserInput("index").match(/(const SENTENCE)/g), "SENTENCE should be a constant variable declared with const.");' + - text: i debe ser declarada con let . + testString: 'getUserInput => assert(getUserInput("index").match(/(let i)/g), "i should be declared with let.");' + - text: console.log debe cambiar para imprimir la variable SENTENCE . + testString: 'getUserInput => assert(getUserInput("index").match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g), "console.log should be adjusted to print the variable SENTENCE.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function printManyTimes(str) { + "use strict"; + + // change code below this line + + var sentence = str + " is cool!"; + for(var i = 0; i < str.length; i+=2) { + console.log(sentence); + } + + // change code above this line + +} +printManyTimes("freeCodeCamp"); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.spanish.md new file mode 100644 index 0000000000..e8f12c6747 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/explore-differences-between-the-var-and-let-keywords.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7b87367417b2b2512b3f +title: Explore Differences Between the var and let Keywords +localeTitle: Explora las diferencias entre la var y deja palabras clave +challengeType: 1 +--- + +## Description +
    +Uno de los mayores problemas con la declaración de variables con la palabra clave var es que puede sobrescribir las declaraciones de variables sin un error. +
    var camper = 'James';
    var camper = 'David';
    console.log(camper);
    // logs 'David'
    +Como puede ver en el código anterior, la variable camper se declaró originalmente como James y luego se anuló para ser David . +En una aplicación pequeña, es posible que no tenga este tipo de problema, pero cuando su código se hace más grande, puede sobrescribir accidentalmente una variable que no pretendía sobrescribir. +Debido a que este comportamiento no produce un error, la búsqueda y solución de errores se vuelve más difícil.
    +Se introdujo una nueva palabra clave llamada let en ES6 para resolver este problema potencial con la palabra clave var . +Si tuviera que reemplazar var por let en las declaraciones de variables del código anterior, el resultado sería un error. +
    let camper = 'James';
    let camper = 'David'; // throws an error
    +Este error se puede ver en la consola de su navegador. +Entonces, a diferencia de var , cuando se usa let , una variable con el mismo nombre solo se puede declarar una vez. +Tenga en cuenta el "use strict" . Esto habilita el modo estricto, que detecta errores comunes de codificación y acciones "inseguras". Por ejemplo: +
    "use strict";
    x = 3.14; // throws an error because x is not declared
    +
    + +## Instructions +
    +Actualizar el código para que solo use la palabra clave let . +
    + +## Tests +
    + +```yml +tests: + - text: var no existe en el código. + testString: 'getUserInput => assert(!getUserInput("index").match(/var/g),"var does not exist in code.");' + - text: catName debe ser Oliver . + testString: 'assert(catName === "Oliver", "catName should be Oliver.");' + - text: quote debe ser "Oliver says Meow!" + testString: 'assert(quote === "Oliver says Meow!", "quote should be "Oliver says Meow!"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +var catName; +var quote; +function catTalk() { + "use strict"; + + catName = "Oliver"; + quote = catName + " says Meow!"; + +} +catTalk(); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.spanish.md new file mode 100644 index 0000000000..2eaeecd3c9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/import-a-default-export.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d7b8d367417b2b2512b59 +title: Import a Default Export +localeTitle: Importar una exportación predeterminada +challengeType: 1 +--- + +## Description +
    +En el último desafío, aprendiste acerca de la export default y sus usos. Es importante tener en cuenta que, para importar una exportación predeterminada, debe usar una sintaxis de import diferente. +En el siguiente ejemplo, tenemos una función, add , que es la exportación predeterminada de un archivo, "math_functions" . Aquí está cómo importarlo: +
    import add from "math_functions";
    add(5,4); //Will return 9
    +La sintaxis difiere en un lugar clave: el valor importado, add , no está rodeado por llaves, {} . A diferencia de los valores exportados, el método principal para importar una exportación predeterminada es simplemente escribir el nombre del valor después de la import . +
    + +## Instructions +
    +En el siguiente código, importe la exportación predeterminada, subtract , del archivo "math_functions" , que se encuentra en el mismo directorio que este archivo. +
    + +## Tests +
    + +```yml +tests: + - text: Importa adecuadamente export default método export default . + testString: 'getUserInput => assert(getUserInput("index").match(/import\s+subtract\s+from\s+"math_functions"/g), "Properly imports export default method.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +"use strict"; +subtract(7,4); +``` + +
    + +### Before Test +
    + +```js +window.require = function(str) { +if (str === 'math_functions') { +return function(a, b) { +return a - b; +}}}; +``` + +
    + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.spanish.md new file mode 100644 index 0000000000..69ba7f181d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const.spanish.md @@ -0,0 +1,70 @@ +--- +id: 587d7b87367417b2b2512b42 +title: Mutate an Array Declared with const +localeTitle: Mutar una matriz declarada con const +challengeType: 1 +--- + +## Description +
    +La declaración const tiene muchos casos de uso en JavaScript moderno. +Algunos desarrolladores prefieren asignar todas sus variables usando const de forma predeterminada, a menos que sepan que deberán reasignar el valor. Solo en ese caso, usan let . +Sin embargo, es importante comprender que los objetos (incluidas las matrices y las funciones) asignados a una variable que usa const todavía son mutables. El uso de la declaración const solo evita la reasignación del identificador de variable. +
    "use strict";
    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]
    +Como puede ver, puede mutar el objeto [5, 6, 7] sí mismo y la variable s seguirá apuntando a la matriz alterada [5, 6, 45] . Al igual que todas las matrices, los elementos de la matriz en s son mutables, pero debido a que se utilizó const , no puede usar el identificador de la variable s para apuntar a una matriz diferente mediante el operador de asignación. +
    + +## Instructions +
    +Una matriz se declara como const s = [5, 7, 2] . Cambie la matriz a [2, 5, 7] usando varias asignaciones de elementos. +
    + +## Tests +
    + +```yml +tests: + - text: No reemplace la palabra clave const . + testString: 'getUserInput => assert(getUserInput("index").match(/const/g), "Do not replace const keyword.");' + - text: s debe ser una variable constante (usando const ). + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+s/g), "s should be a constant variable (by using const).");' + - text: No cambie la declaración original de la matriz. + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+s\s*=\s*\[\s*5\s*,\s*7\s*,\s*2\s*\]\s*;?/g), "Do not change the original array declaration.");' + - text: ' s debe ser igual a [2, 5, 7] .' + testString: 'assert.deepEqual(s, [2, 5, 7], "s should be equal to [2, 5, 7].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const s = [5, 7, 2]; +function editInPlace() { + "use strict"; + // change code below this line + + // s = [2, 5, 7]; <- this is invalid + + // change code above this line +} +editInPlace(); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.spanish.md new file mode 100644 index 0000000000..9d566a0253 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/prevent-object-mutation.spanish.md @@ -0,0 +1,75 @@ +--- +id: 598f48a36c8c40764b4e52b3 +title: Prevent Object Mutation +localeTitle: Prevenir la mutación de objetos +challengeType: 1 +--- + +## Description +
    +Como se vio en el desafío anterior, la declaración const por sí sola no protege realmente sus datos de la mutación. Para garantizar que sus datos no cambien, JavaScript proporciona una función Object.freeze para evitar la mutación de datos. +Una vez que el objeto está congelado, ya no puede agregar, actualizar o eliminar propiedades de él. Cualquier intento de cambiar el objeto será rechazado sin un error. +
    let obj = {
      name:"FreeCodeCamp",
      review:"Awesome"
    };
    Object.freeze(obj);
    obj.review = "bad"; //will be ignored. Mutation not allowed
    obj.newProp = "Test"; // will be ignored. Mutation not allowed
    console.log(obj);
    // { name: "FreeCodeCamp", review:"Awesome"}
    +
    + +## Instructions +
    +En este desafío, Object.freeze para evitar que Object.freeze las constantes matemáticas. MATH_CONSTANTS congelar el objeto MATH_CONSTANTS para que nadie pueda alterar el valor de PI , agregar o eliminar propiedades. +
    + +## Tests +
    + +```yml +tests: + - text: No reemplace la palabra clave const . + testString: 'getUserInput => assert(getUserInput("index").match(/const/g), "Do not replace const keyword.");' + - text: MATH_CONSTANTS debe ser una variable constante (usando const ). + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+MATH_CONSTANTS/g), "MATH_CONSTANTS should be a constant variable (by using const).");' + - text: No cambie los MATH_CONSTANTS originales. + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+MATH_CONSTANTS\s+=\s+{\s+PI:\s+3.14\s+};/g), "Do not change original MATH_CONSTANTS.");' + - text: PI es igual a 3.14 . + testString: 'assert(PI === 3.14, "PI equals 3.14.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function freezeObj() { + "use strict"; + const MATH_CONSTANTS = { + PI: 3.14 + }; + // change code below this line + + + // change code above this line + try { + MATH_CONSTANTS.PI = 99; + } catch( ex ) { + console.log(ex); + } + return MATH_CONSTANTS.PI; +} +const PI = freezeObj(); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.spanish.md new file mode 100644 index 0000000000..68999d558e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7b88367417b2b2512b46 +title: Set Default Parameters for Your Functions +localeTitle: Establecer parámetros predeterminados para sus funciones +challengeType: 1 +--- + +## Description +
    +Para ayudarnos a crear funciones más flexibles, ES6 introduce parámetros predeterminados para las funciones. +Echa un vistazo a este código: +
    function greeting(name = "Anonymous") {
      return "Hello " + name;
    }
    console.log(greeting("John")); // Hello John
    console.log(greeting()); // Hello Anonymous
    +El parámetro predeterminado se activa cuando el argumento no está especificado (no está definido). Como puede ver en el ejemplo anterior, el name del parámetro recibirá su valor predeterminado "Anonymous" cuando no proporcione un valor para el parámetro. Puede agregar valores predeterminados para tantos parámetros como desee. +
    + +## Instructions +
    +Modifique el increment la función agregando parámetros predeterminados para que agregue 1 al number si no se especifica el value . +
    + +## Tests +
    + +```yml +tests: + - text: 'El resultado del increment(5, 2) debe ser 7 '. + testString: 'assert(increment(5, 2) === 7, "The result of increment(5, 2) should be 7.");' + - text: El resultado del increment(5) debe ser 6 . + testString: 'assert(increment(5) === 6, "The result of increment(5) should be 6.");' + - text: se usó el parámetro por defecto 1 para el value . + testString: 'getUserInput => assert(getUserInput("index").match(/value\s*=\s*1/g), "default parameter 1 was used for value.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const increment = (function() { + "use strict"; + return function increment(number, value) { + return number + value; + }; +})(); +console.log(increment(5, 2)); // returns 7 +console.log(increment(5)); // returns 6 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/understand-the-differences-between-import-and-require.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/understand-the-differences-between-import-and-require.spanish.md new file mode 100644 index 0000000000..a01e794f1c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/understand-the-differences-between-import-and-require.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7b8c367417b2b2512b55 +title: Understand the Differences Between import and require +localeTitle: Comprender las diferencias entre importar y requerir +challengeType: 1 +--- + +## Description +
    +En el pasado, la función require() se usaría para importar las funciones y el código en archivos y módulos externos. Aunque es práctico, esto presenta un problema: algunos archivos y módulos son bastante grandes, y es posible que solo necesite cierto código de esos recursos externos. +ES6 nos da una herramienta muy útil conocida como importación . Con él, podemos elegir qué partes de un módulo o archivo cargar en un archivo dado, ahorrando tiempo y memoria. +Considera el siguiente ejemplo. Imagine que math_array_functions tiene aproximadamente 20 funciones, pero solo necesito una, countItems , en mi archivo actual. El antiguo enfoque de require() me obligaría a incorporar las 20 funciones. Con esta nueva sintaxis de import , puedo traer solo la función deseada, así: +
    import { countItems } from "math_array_functions"
    +Una descripción del código anterior: +
    import { function } from "file_path_goes_here"
    // We can also import variables the same way!
    +Hay algunas formas de escribir una declaración de import , pero la anterior es un caso de uso muy común. +Nota
    El espacio en blanco que rodea la función dentro de las llaves es una buena práctica: facilita la lectura de la declaración de import . +Nota
    Las lecciones en esta sección manejan características que no son del navegador. import , y las declaraciones que presentamos en el resto de estas lecciones, no funcionarán directamente en un navegador. Sin embargo, podemos usar varias herramientas para crear código a partir de esto para que funcione en el navegador. +Nota
    En la mayoría de los casos, la ruta del archivo requiere una ./ antes de ella; de lo contrario, el nodo buscará en el directorio node_modules primero intentando cargarlo como una dependencia. +
    + +## Instructions +
    +Agregue la declaración de import apropiada que permitirá que el archivo actual use la función capitalizeString . El archivo donde vive esta función se llama "string_functions" , y está en el mismo directorio que el archivo actual. +
    + +## Tests +
    + +```yml +tests: + - text: declaración de import válida + testString: 'getUserInput => assert(getUserInput("index").match(/import\s+\{\s*capitalizeString\s*\}\s+from\s+("|")string_functions\1/g), "valid import statement");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +"use strict"; +capitalizeString("hello!"); +``` + +
    + +### Before Test +
    + +```js +window.require = function (str) { +if (str === 'string_functions') { +return { +capitalizeString: str => str.toUpperCase() +}}}; +``` + +
    + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.spanish.md new file mode 100644 index 0000000000..9349d4e56e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use--to-import-everything-from-a-file.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b8c367417b2b2512b57 +title: Use * to Import Everything from a File +localeTitle: Usa * para importar todo desde un archivo +challengeType: 1 +--- + +## Description +
    +Suponga que tiene un archivo que desea importar todo su contenido en el archivo actual. Esto se puede hacer con la sintaxis de importación * . +Aquí hay un ejemplo donde el contenido de un archivo llamado "math_functions" se importa a un archivo en el mismo directorio: +
    import * as myMathModule from "math_functions";
    myMathModule.add(2,3);
    myMathModule.subtract(5,3);
    +Y rompiendo ese código: +
    import * as object_with_name_of_your_choice from "file_path_goes_here"
    object_with_name_of_your_choice.imported_function
    +Puede usar cualquier nombre después de la import * as parte de la declaración. Para utilizar este método, se requiere un objeto que reciba los valores importados. Desde aquí, utilizará la notación de puntos para llamar a sus valores importados. +
    + +## Instructions +
    +El siguiente código requiere el contenido de un archivo, "capitalize_strings" , que se encuentra en el mismo directorio que este, importado. Agregue la declaración de import * apropiada en la parte superior del archivo, utilizando el objeto proporcionado. +
    + +## Tests +
    + +```yml +tests: + - text: Utiliza correctamente import * as sintaxis. + testString: 'assert(code.match(/import\s+\*\s+as\s+[a-zA-Z0-9_$]+\s+from\s*"\s*capitalize_strings\s*"\s*;/gi), "Properly uses import * as syntax.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +"use strict"; +``` + +
    + +### Before Test +
    + +```js +window.require = function(str) { +if (str === 'capitalize_strings') { +return { +capitalize: str => str.toUpperCase(), +lowercase: str => str.toLowerCase() +}}}; +``` + +
    + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.spanish.md new file mode 100644 index 0000000000..45bc486368 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-arrow-functions-to-write-concise-anonymous-functions.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b87367417b2b2512b43 +title: Use Arrow Functions to Write Concise Anonymous Functions +localeTitle: Utilice las funciones de flecha para escribir funciones anónimas concisas +challengeType: 1 +--- + +## Description +
    +En JavaScript, a menudo no necesitamos nombrar nuestras funciones, especialmente cuando se pasa una función como argumento a otra función. En su lugar, creamos funciones en línea. No necesitamos nombrar estas funciones porque no las reutilizamos en ningún otro lugar. +Para lograr esto, a menudo usamos la siguiente sintaxis: +
    const myFunc = function() {
      const myVar = "value";
      return myVar;
    }
    +ES6 nos proporciona el azúcar sintáctico para no tener que escribir funciones anónimas de esta manera. En su lugar, puede utilizar la sintaxis de la función de flecha : +
    const myFunc = () => {
      const myVar = "value";
      return myVar;
    }
    +Cuando no hay un cuerpo de función, y solo un valor de retorno, la sintaxis de la función de flecha le permite omitir el return la palabra clave, así como los corchetes que rodean el código. Esto ayuda a simplificar funciones más pequeñas en declaraciones de una línea: +
    const myFunc = () => "value"
    +Este código seguirá devolviendo value por defecto. +
    + +## Instructions +
    +Reescriba la función asignada a la variable magic que devuelve una nueva Date() para usar la sintaxis de la función de flecha. También asegúrese de que no se define nada usando la palabra clave var . +
    + +## Tests +
    + +```yml +tests: + - text: El usuario reemplazó la palabra clave var . + testString: 'getUserInput => assert(!getUserInput("index").match(/var/g), "User did replace var keyword.");' + - text: magic debe ser una variable constante (usando const ). + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+magic/g), "magic should be a constant variable (by using const).");' + - text: magic es una function . + testString: 'assert(typeof magic === "function", "magic is a function.");' + - text: magic() devuelve la fecha correcta. + testString: 'assert(magic().getDate() == new Date().getDate(), "magic() returns correct date.");' + - text: function palabra clave de la function no se utilizó. + testString: 'getUserInput => assert(!getUserInput("index").match(/function/g), "function keyword was not used.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +var magic = function() { + "use strict"; + return new Date(); +}; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.spanish.md new file mode 100644 index 0000000000..2c22e8f7bc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7b8b367417b2b2512b53 +title: Use class Syntax to Define a Constructor Function +localeTitle: Use la clase Sintaxis para definir una función constructora +challengeType: 1 +--- + +## Description +
    +ES6 proporciona una nueva sintaxis para ayudar a crear objetos, utilizando la clase de palabra clave. +Esto debe notarse, que la sintaxis de class es solo una sintaxis, y no una implementación de paradigmas orientados a objetos basada en clases de pleno derecho, a diferencia de lenguajes como Java, Python, o Ruby, etc. +En ES5, generalmente definimos una función constructora, y use la new palabra clave para crear una instancia de un objeto. +
    var SpaceShuttle = function(targetPlanet){
      this.targetPlanet = targetPlanet;
    }
    var zeus = new SpaceShuttle('Jupiter');
    +La sintaxis de la clase simplemente reemplaza la creación de la función de constructor: +
    class SpaceShuttle {
      constructor(targetPlanet){
        this.targetPlanet = targetPlanet;
      }
    }
    const zeus = new SpaceShuttle('Jupiter');
    +Tenga en cuenta que la class se añadió la palabra clave declara una nueva función, y un constructor, que se invoca cuando new se llama - para crear un nuevo objeto. +
    + +## Instructions +
    +Use class palabra clave de class y escriba un constructor adecuado para crear la clase Vegetable . +El Vegetable permite crear un objeto vegetal, con un name propiedad, que se pasará al constructor. +
    + +## Tests +
    + +```yml +tests: + - text: Vegetable debe ser una class con un método constructor definido. + testString: 'assert(typeof Vegetable === "function" && typeof Vegetable.constructor === "function", "Vegetable should be a class with a defined constructor method.");' + - text: Se usó la palabra clave de class . + testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"class keyword was used.");' + - text: Vegetable puede ser instanciado. + testString: 'assert(() => {const a = new Vegetable("apple"); return typeof a === "object";},"Vegetable can be instantiated.");' + - text: carrot.name debe devolver la carrot . + testString: 'assert(carrot.name=="carrot","carrot.name should return carrot.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function makeClass() { + "use strict"; + /* Alter code below this line */ + + /* Alter code above this line */ + return Vegetable; +} +const Vegetable = makeClass(); +const carrot = new Vegetable('carrot'); +console.log(carrot.name); // => should be 'carrot' +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.spanish.md new file mode 100644 index 0000000000..7aaa81c19c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-arrays.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b89367417b2b2512b4b +title: Use Destructuring Assignment to Assign Variables from Arrays +localeTitle: Utilice la asignación de destrucción para asignar variables de matrices +challengeType: 1 +--- + +## Description +
    +ES6 hace que la desestructuración de matrices sea tan fácil como desestructurar objetos. +Una diferencia clave entre el operador de propagación y la desestructuración de matrices es que el operador de propagación desempaqueta todo el contenido de una matriz en una lista separada por comas. Por consiguiente, no puede seleccionar o elegir qué elementos desea asignar a las variables. +destrucción de una matriz nos permite hacer exactamente eso: +
    const [a, b] = [1, 2, 3, 4, 5, 6];
    console.log(a, b); // 1, 2
    +A la variable a se le asigna el primer valor de la matriz, b se le asigna el segundo valor de la matriz. +También podemos acceder al valor en cualquier índice en una matriz con desestructuración usando comas para alcanzar el índice deseado: +
    const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
    console.log(a, b, c); // 1, 2, 5
    +
    + +## Instructions +
    +Use la asignación de desestructuración para intercambiar los valores de a y b modo que a reciba el valor almacenado en b , y b reciba el valor almacenado en a . +
    + +## Tests +
    + +```yml +tests: + - text: 'El valor de a debe ser 6, después del intercambio.' + testString: 'assert(a === 6, "Value of a should be 6, after swapping.");' + - text: 'El valor de b debería ser 8, después del intercambio.' + testString: 'assert(b === 8, "Value of b should be 8, after swapping.");' + - text: Utilice la desestructuración de matrices para intercambiar a y b. + testString: '// assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code), "Use array destructuring to swap a and b.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let a = 8, b = 6; +(() => { + "use strict"; + // change code below this line + + // change code above this line +})(); +console.log(a); // should be 6 +console.log(b); // should be 8 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.spanish.md new file mode 100644 index 0000000000..3fc1653da3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-nested-objects.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b89367417b2b2512b4a +title: Use Destructuring Assignment to Assign Variables from Nested Objects +localeTitle: Utilice la asignación de destrucción para asignar variables de objetos anidados +challengeType: 1 +--- + +## Description +
    +Podemos igualmente destruir objetos anidados en variables. +Considera el siguiente código: +
    const a = {
      start: { x: 5, y: 6},
      end: { x: 6, y: -9 }
    };
    const { start : { x: startX, y: startY }} = a;
    console.log(startX, startY); // 5, 6
    +En el ejemplo anterior, a la variable start se le asigna el valor de a.start , que también es un objeto. +
    + +## Instructions +
    +Utilice la asignación de desestructuración para obtener el max de forecast.tomorrow y asignarlo a maxOfTomorrow . +
    + +## Tests +
    + +```yml +tests: + - text: maxOfTomorrow es igual a 84.6 + testString: 'assert(getMaxOfTmrw(LOCAL_FORECAST) === 84.6, "maxOfTomorrow equals 84.6");' + - text: se utilizó desestructuración anidada + testString: 'getUserInput => assert(getUserInput("index").match(/\{\s*tomorrow\s*:\s*\{\s*max\s*:\s*maxOfTomorrow\s*\}\s*\}\s*=\s*forecast/g),"nested destructuring was used");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const LOCAL_FORECAST = { + today: { min: 72, max: 83 }, + tomorrow: { min: 73.3, max: 84.6 } +}; + +function getMaxOfTmrw(forecast) { + "use strict"; + // change code below this line + const maxOfTomorrow = undefined; // change this line + // change code above this line + return maxOfTomorrow; +} + +console.log(getMaxOfTmrw(LOCAL_FORECAST)); // should be 84.6 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.spanish.md new file mode 100644 index 0000000000..9926b1e757 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-assign-variables-from-objects.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d7b89367417b2b2512b49 +title: Use Destructuring Assignment to Assign Variables from Objects +localeTitle: Usar asignación de destrucción para asignar variables de objetos +challengeType: 1 +--- + +## Description +
    +Ya vimos cómo el operador de propagación puede difundir o desempaquetar efectivamente el contenido de la matriz. +Podemos hacer algo similar con los objetos también. La asignación de destrucción es una sintaxis especial para asignar cuidadosamente valores tomados directamente de un objeto a variables. +Considera el siguiente código ES5: +
    var voxel = {x: 3.6, y: 7.4, z: 6.54 };
    var x = voxel.x; // x = 3.6
    var y = voxel.y; // y = 7.4
    var z = voxel.z; // z = 6.54
    +Aquí está la misma declaración de asignación con la sintaxis de desestructuración ES6: +
    const { x, y, z } = voxel; // x = 3.6, y = 7.4, z = 6.54
    +Si, por el contrario, desea almacenar los valores de voxel.x en a , voxel.y en b , y voxel.z en c , también tiene esa libertad. +
    const { x : a, y : b, z : c } = voxel // a = 3.6, b = 7.4, c = 6.54
    +Puede leerlo como "obtener el campo x y copiar el valor en a ", y así sucesivamente. +
    + +## Instructions +
    +Use la desestructuración para obtener la temperatura promedio para mañana del objeto de entrada AVG_TEMPERATURES , y asigne un valor con la clave tomorrow a tempOfTomorrow en línea. +
    + +## Tests +
    + +```yml +tests: + - text: getTempOfTmrw(AVG_TEMPERATURES) debe ser 79 + testString: 'assert(getTempOfTmrw(AVG_TEMPERATURES) === 79, "getTempOfTmrw(AVG_TEMPERATURES) should be 79");' + - text: Se utilizó desestructuración con reasignación. + testString: 'getUserInput => assert(getUserInput("index").match(/\{\s*tomorrow\s*:\s*tempOfTomorrow\s*}\s*=\s*avgTemperatures/g),"destructuring with reassignment was used");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const AVG_TEMPERATURES = { + today: 77.5, + tomorrow: 79 +}; + +function getTempOfTmrw(avgTemperatures) { + "use strict"; + // change code below this line + const tempOfTomorrow = undefined; // change this line + // change code above this line + return tempOfTomorrow; +} + +console.log(getTempOfTmrw(AVG_TEMPERATURES)); // should be 79 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.spanish.md new file mode 100644 index 0000000000..99e840a3a3 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d7b8a367417b2b2512b4d +title: Use Destructuring Assignment to Pass an Object as a Function's Parameters +localeTitle: Utilice la asignación de destrucción para pasar un objeto como parámetros de una función +challengeType: 1 +--- + +## Description +
    +En algunos casos, puede destruir el objeto en el propio argumento de una función. +Considera el siguiente código: +
    const profileUpdate = (profileData) => {
      const { name, age, nationality, location } = profileData;
      // do something with these variables
    }
    +Esto destruye efectivamente el objeto enviado a la función. Esto también se puede hacer en el lugar: +
    const profileUpdate = ({ name, age, nationality, location }) => {
      /* do something with these fields */
    }
    +Esto elimina algunas líneas adicionales y hace que nuestro código se vea limpio. +Esto tiene el beneficio adicional de no tener que manipular un objeto completo en una función; solo los campos que son necesarios se copian dentro de la función. +
    + +## Instructions +
    +Use la asignación de desestructuración dentro del argumento de la función half para enviar solo max y min dentro de la función. +
    + +## Tests +
    + +```yml +tests: + - text: stats deben ser un object . + testString: 'assert(typeof stats === "object", "stats should be an object.");' + - text: half(stats) debe ser 28.015 + testString: 'assert(half(stats) === 28.015, "half(stats) should be 28.015");' + - text: Se utilizó la destrucción. + testString: 'getUserInput => assert(getUserInput("index").match(/\(\s*\{\s*\w+\s*,\s*\w+\s*\}\s*\)/g), "Destructuring was used.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const stats = { + max: 56.78, + standard_deviation: 4.34, + median: 34.54, + mode: 23.87, + min: -0.75, + average: 35.85 +}; +const half = (function() { + "use strict"; // do not change this line + + // change code below this line + return function half(stats) { + // use function argument destructuring + return (stats.max + stats.min) / 2.0; + }; + // change code above this line + +})(); +console.log(stats); // should be object +console.log(half(stats)); // should be 28.015 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements.spanish.md new file mode 100644 index 0000000000..59389b05c8 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-operator-to-reassign-array-elements.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b8a367417b2b2512b4c +title: Use Destructuring Assignment with the Rest Operator to Reassign Array Elements +localeTitle: Utilice la asignación de destrucción con el operador de reposo para reasignar elementos de matriz +challengeType: 1 +--- + +## Description +
    +En algunas situaciones que involucran la desestructuración de matrices, podríamos querer recopilar el resto de los elementos en una matriz separada. +El resultado es similar a Array.prototype.slice() , como se muestra a continuación: +
    const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
    console.log(a, b); // 1, 2
    console.log(arr); // [3, 4, 5, 7]
    +Las variables a y b toman los valores primero y segundo de la matriz. Después de eso, debido a la presencia del operador en reposo, arr obtiene el resto de los valores en forma de una matriz. +El elemento resto solo funciona correctamente como la última variable en la lista. Como en, no puede usar el operador de descanso para capturar un subarreglo que omita el último elemento de la matriz original. +
    + +## Instructions +
    +Use la asignación de desestructuración con el operador de descanso para realizar un Array.prototype.slice() efectivo de manera que arr sea ​​una sub-matriz de la source de la matriz original con los dos primeros elementos omitidos. +
    + +## Tests +
    + +```yml +tests: + - text: ' arr debería ser [3,4,5,6,7,8,9,10] ' + testString: 'assert(arr.every((v, i) => v === i + 3) && arr.length === 8,"arr should be [3,4,5,6,7,8,9,10]");' + - text: Se debe utilizar la destrucción. + testString: 'getUserInput => assert(getUserInput("index").match(/\[\s*\w*\s*,\s*\w*\s*,\s*...\w+\s*\]/g),"Destructuring should be used.");' + - text: Array.slice() no debe utilizarse. + testString: 'getUserInput => assert(!getUserInput("index").match(/slice/g), "Array.slice() should not be used.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const source = [1,2,3,4,5,6,7,8,9,10]; +function removeFirstTwo(list) { + "use strict"; + // change code below this line + arr = list; // change this + // change code above this line + return arr; +} +const arr = removeFirstTwo(source); +console.log(arr); // should be [3,4,5,6,7,8,9,10] +console.log(source); // should be [1,2,3,4,5,6,7,8,9,10]; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-export-to-reuse-a-code-block.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-export-to-reuse-a-code-block.spanish.md new file mode 100644 index 0000000000..5b49489675 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-export-to-reuse-a-code-block.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7b8c367417b2b2512b56 +title: Use export to Reuse a Code Block +localeTitle: Usar la exportación para reutilizar un bloque de código +challengeType: 1 +--- + +## Description +
    +En el desafío anterior, aprendió acerca de la import y cómo se puede aprovechar para importar pequeñas cantidades de código de archivos grandes. Sin embargo, para que esto funcione, debemos utilizar una de las declaraciones que acompañan a la import , conocida como exportación . Cuando queremos que un código, una función o una variable, se pueda utilizar en otro archivo, debemos exportarlo para importarlo en otro archivo. Al igual que la import , la export es una característica que no es del navegador. +Lo siguiente es lo que llamamos una exportación con nombre . Con esto, podemos importar cualquier código que exportemos a otro archivo con la sintaxis de import que aprendió en la última lección. Aquí hay un ejemplo: +
    const capitalizeString = (string) => {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    export { capitalizeString } //How to export functions.
    export const foo = "bar"; //How to export variables.
    +Alternativamente, si desea compactar todas sus declaraciones de export en una sola línea, puede adoptar este enfoque: +
    const capitalizeString = (string) => {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    const foo = "bar";
    export { capitalizeString, foo }
    +Cualquiera de los dos enfoques es perfectamente aceptable. +
    + +## Instructions +
    +A continuación hay dos variables que quiero que estén disponibles para que otros archivos las utilicen. Utilizando la primera forma en que demostré export , exportamos las dos variables. +
    + +## Tests +
    + +```yml +tests: + - text: foo se exporta. + testString: 'getUserInput => assert(getUserInput("index").match(/export\s+const\s+foo\s*=\s*"bar"/g), "foo is exported.");' + - text: bar se exporta. + testString: 'getUserInput => assert(getUserInput("index").match(/export\s+const\s+bar\s*=\s*"foo"/g), "bar is exported.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +"use strict"; +const foo = "bar"; +const bar = "foo"; +``` + +
    + +### Before Test +
    + +```js +window.exports = function(){}; +``` + +
    + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.spanish.md new file mode 100644 index 0000000000..47efa149c6 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-getters-and-setters-to-control-access-to-an-object.spanish.md @@ -0,0 +1,78 @@ +--- +id: 587d7b8c367417b2b2512b54 +title: Use getters and setters to Control Access to an Object +localeTitle: Usar getters y setters para controlar el acceso a un objeto +challengeType: 1 +--- + +## Description +
    +Puede obtener valores de un objeto y establecer un valor de una propiedad dentro de un objeto. +Estos se llaman clásicamente getters y setters . +funciones de Getter están destinadas a simplemente devolver (obtener) el valor de la variable privada de un objeto al usuario sin que el usuario acceda directamente a la variable privada. +funciones de Setter están destinadas a modificar (establecer) el valor de la variable privada de un objeto en función del valor pasado a la función de establecimiento. Este cambio podría implicar cálculos, o incluso sobrescribir completamente el valor anterior. +
    class Book {
      constructor(author) {
        this._author = author;
      }
      // getter
      get writer(){
        return this._author;
      }
      // setter
      set writer(updatedAuthor){
        this._author = updatedAuthor;
      }
    }
    const lol = new Book('anonymous');
    console.log(lol.writer);  // anonymous
    lol.writer = 'wut';
    console.log(lol.writer);  // wut
    +Observe la sintaxis que estamos utilizando para invocar al captador y al configurador, como si no fueran siquiera funciones. +Getters y setters son importantes, ya que ocultan los detalles de la implementación interna. +
    + +## Instructions +
    +Use class palabra clave de la class para crear una clase de termostato. El constructor acepta la temperatura Fahrenheit. +Ahora cree el getter y el setter en la clase, para obtener la temperatura en la escala Celsius. +Recuerde que C = 5/9 * (F - 32) y F = C * 9.0 / 5 + 32 , donde F es el valor de la temperatura en la escala Fahrenheit, y C es el valor de la misma temperatura en la escala Celsius +Nota +Cuando implementes esto, estarás siguiendo la temperatura dentro de la clase en una escala, ya sea Fahrenheit o Celsius. +Este es el poder de getter o setter: está creando una API para otro usuario, que obtendría el resultado correcto, sin importar de cuál sea el seguimiento. +En otras palabras, está abstrayendo los detalles de implementación del consumidor. +
    + +## Tests +
    + +```yml +tests: + - text: Thermostat debe ser una class con un método constructor definido. + testString: 'assert(typeof Thermostat === "function" && typeof Thermostat.constructor === "function","Thermostat should be a class with a defined constructor method.");' + - text: Se usó la palabra clave de class . + testString: 'getUserInput => assert(getUserInput("index").match(/class/g),"class keyword was used.");' + - text: Thermostat puede ser instanciado. + testString: 'assert(() => {const t = new Thermostat(32); return typeof t === "object" && t.temperature === 0;}, "Thermostat can be instantiated.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function makeClass() { + "use strict"; + /* Alter code below this line */ + + /* Alter code above this line */ + return Thermostat; +} +const Thermostat = makeClass(); +const thermos = new Thermostat(76); // setting in Fahrenheit scale +let temp = thermos.temperature; // 24.44 in C +thermos.temperature = 26; +temp = thermos.temperature; // 26 in C +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters.spanish.md new file mode 100644 index 0000000000..316aa9d0c2 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-rest-operator-with-function-parameters.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b88367417b2b2512b47 +title: Use the Rest Operator with Function Parameters +localeTitle: Utilice el operador de reposo con parámetros de función +challengeType: 1 +--- + +## Description +
    +Para ayudarnos a crear funciones más flexibles, ES6 presenta al operador de resto para los parámetros de función. Con el operador resto, puede crear funciones que toman un número variable de argumentos. Estos argumentos se almacenan en una matriz a la que se puede acceder posteriormente desde dentro de la función. +Echa un vistazo a este código: +
    function howMany(...args) {
      return "You have passed " + args.length + " arguments.";
    }
    console.log(howMany(0, 1, 2)); // You have passed 3 arguments
    console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
    +El operador restante elimina la necesidad de verificar la matriz de args y nos permite aplicar map() , filter() y reduce() en la matriz de parámetros. +
    + +## Instructions +
    +Modifique la sum la función para que use el operador de descanso y funcione de la misma manera con cualquier número de parámetros. +
    + +## Tests +
    + +```yml +tests: + - text: 'El resultado de la sum(0,1,2) debe ser 3' + testString: 'assert(sum(0,1,2) === 3, "The result of sum(0,1,2) should be 3");' + - text: 'El resultado de la sum(1,2,3,4) debe ser 10' + testString: 'assert(sum(1,2,3,4) === 10, "The result of sum(1,2,3,4) should be 10");' + - text: El resultado de la sum(5) debe ser 5. + testString: 'assert(sum(5) === 5, "The result of sum(5) should be 5");' + - text: El resultado de sum() debe ser 0 + testString: 'assert(sum() === 0, "The result of sum() should be 0");' + - text: La función de sum usa el operador de ... propagación en el parámetro args . + testString: 'getUserInput => assert(getUserInput("index").match(/function\s+sum\s*\(\s*...args\s*\)\s*{/g), "The sum function uses the ... spread operator on the args parameter.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const sum = (function() { + "use strict"; + return function sum(x, y, z) { + const args = [ x, y, z ]; + return args.reduce((a, b) => a + b, 0); + }; +})(); +console.log(sum(1, 2, 3)); // 6 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.spanish.md new file mode 100644 index 0000000000..7137334c6f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/use-the-spread-operator-to-evaluate-arrays-in-place.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b89367417b2b2512b48 +title: Use the Spread Operator to Evaluate Arrays In-Place +localeTitle: Utilice el operador de propagación para evaluar matrices en el lugar +challengeType: 1 +--- + +## Description +
    +ES6 presenta el operador de propagación , que nos permite expandir arreglos y otras expresiones en lugares donde se esperan múltiples parámetros o elementos. +El siguiente código de ES5 utiliza apply() para calcular el valor máximo en una matriz: +
    var arr = [6, 89, 3, 45];
    var maximus = Math.max.apply(null, arr); // returns 89
    +Tuvimos que usar Math.max.apply(null, arr) porque Math.max(arr) devuelve NaN . Math.max() espera argumentos separados por comas, pero no una matriz. +El operador de difusión hace que esta sintaxis sea mucho mejor para leer y mantener. +
    const arr = [6, 89, 3, 45];
    const maximus = Math.max(...arr); // returns 89
    +...arr devuelve una matriz desempaquetada. En otras palabras, se propaga la matriz. +Sin embargo, el operador de difusión solo funciona en el lugar, como en un argumento a una función o en un literal de matriz. El siguiente código no funcionará: +
    const spreaded = ...arr; // will throw a syntax error
    +
    + +## Instructions +
    +Copie todos los contenidos de arr1 en otra matriz arr2 utilizando el operador de propagación. +
    + +## Tests +
    + +```yml +tests: + - text: arr2 es la copia correcta de arr1 . + testString: 'assert(arr2.every((v, i) => v === arr1[i]), "arr2 is correct copy of arr1.");' + - text: ... se usó el operador spread para duplicar arr1 . + testString: 'getUserInput => assert(getUserInput("index").match(/\[\s*...arr1\s*\]/g),"... spread operator was used to duplicate arr1.");' + - text: arr2 permanece sin cambios cuando se cambia arr1 . + testString: 'assert((arr1, arr2) => {arr1.push("JUN"); return arr2.length < arr1.length},"arr2 remains unchanged when arr1 is changed.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const arr1 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY']; +let arr2; +(function() { + "use strict"; + arr2 = []; // change this line +})(); +console.log(arr2); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.spanish.md new file mode 100644 index 0000000000..2fc14d78b8 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-arrow-functions-with-parameters.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d7b88367417b2b2512b44 +title: Write Arrow Functions with Parameters +localeTitle: Escribir funciones de flecha con parámetros +challengeType: 1 +--- + +## Description +
    +Al igual que una función normal, puede pasar argumentos a las funciones de flecha. +
    // doubles input value and returns it
    const doubler = (item) => item * 2;
    +También puede pasar más de un argumento a las funciones de flecha. +
    + +## Instructions +
    +Vuelva a myConcat función myConcat que agrega el contenido de arr2 a arr1 para que la función utilice la sintaxis de la función de flecha. +
    + +## Tests +
    + +```yml +tests: + - text: El usuario reemplazó la palabra clave var . + testString: 'getUserInput => assert(!getUserInput("index").match(/var/g), "User did replace var keyword.");' + - text: myConcat debe ser una variable constante (usando const ). + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+myConcat/g), "myConcat should be a constant variable (by using const).");' + - text: myConcat debería ser una función + testString: 'assert(typeof myConcat === "function", "myConcat should be a function");' + - text: myConcat() devuelve la array correcta + testString: 'assert(() => { const a = myConcat([1], [2]); return a[0] == 1 && a[1] == 2; }, "myConcat() returns the correct array");' + - text: function palabra clave de la function no se utilizó. + testString: 'getUserInput => assert(!getUserInput("index").match(/function/g), "function keyword was not used.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +var myConcat = function(arr1, arr2) { + "use strict"; + return arr1.concat(arr2); +}; +// test your code +console.log(myConcat([1, 2], [3, 4, 5])); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.spanish.md new file mode 100644 index 0000000000..218befa4af --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-declarative-functions-with-es6.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7b8b367417b2b2512b50 +title: Write Concise Declarative Functions with ES6 +localeTitle: Escribir funciones declarativas concisas con ES6 +challengeType: 1 +--- + +## Description +
    +Al definir funciones dentro de objetos en ES5, tenemos que usar la function palabra clave de la siguiente manera: +
    const person = {
      name: "Taylor",
      sayHello: function() {
        return `Hello! My name is ${this.name}.`;
      }
    };
    +Con ES6, puede eliminar la palabra clave de function y los dos puntos por completo al definir funciones en objetos. Aquí hay un ejemplo de esta sintaxis: +
    const person = {
      name: "Taylor",
      sayHello() {
        return `Hello! My name is ${this.name}.`;
      }
    };
    +
    + +## Instructions +
    +Refactorice la función setGear dentro de la bicycle objeto para usar la sintaxis abreviada descrita anteriormente. +
    + +## Tests +
    + +```yml +tests: + - text: No se usó la expresión de función tradicional. + testString: 'assert(!getUserInput("index").match(/function/),"Traditional function expression was not used.");' + - text: setGear es una función declarativa. + testString: 'assert(typeof bicycle.setGear === "function" && getUserInput("index").match(/setGear\s*\(.+\)\s*\{/), "setGear is a declarative function.");' + - text: bicycle.setGear (48) cambia el valor de gear a 48. + testString: 'assert((new bicycle.setGear(48)).gear === 48, "bicycle.setGear(48) changes the gear value to 48.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +// change code below this line +const bicycle = { + gear: 2, + setGear: function(newGear) { + "use strict"; + this.gear = newGear; + } +}; +// change code above this line +bicycle.setGear(3); +console.log(bicycle.gear); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-simple-fields.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-simple-fields.spanish.md new file mode 100644 index 0000000000..ede5dfa609 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-concise-object-literal-declarations-using-simple-fields.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7b8a367417b2b2512b4f +title: Write Concise Object Literal Declarations Using Simple Fields +localeTitle: Escriba declaraciones literales de objetos concisos utilizando campos simples +challengeType: 1 +--- + +## Description +
    +ES6 agrega un buen soporte para definir fácilmente literales de objetos. +Considera el siguiente código: +
    const getMousePosition = (x, y) => ({
      x: x,
      y: y
    });
    +getMousePosition es una función simple que devuelve un objeto que contiene dos campos. +ES6 proporciona el azúcar sintáctico para eliminar la redundancia de tener que escribir x: x . Simplemente puede escribir x una vez, y se convertirá a x: x (o algo equivalente) debajo del capó. +Aquí se reescribe la misma función de la anterior para usar esta nueva sintaxis: +
    const getMousePosition = (x, y) => ({ x, y });
    +
    + +## Instructions +
    +Utilice campos simples con objetos literales para crear y devolver un objeto Person . +
    + +## Tests +
    + +```yml +tests: + - text: 'la salida es {name: "Zodiac Hasbro", age: 56, gender: "male"} .' + testString: 'assert(() => {const res={name:"Zodiac Hasbro",age:56,gender:"male"}; const person=createPerson("Zodiac Hasbro", 56, "male"); return Object.keys(person).every(k => person[k] === res[k]);}, "the output is {name: "Zodiac Hasbro", age: 56, gender: "male"}.");' + - text: 'No : fueron utilizados'. + testString: 'getUserInput => assert(!getUserInput("index").match(/:/g), "No : were used.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const createPerson = (name, age, gender) => { + "use strict"; + // change code below this line + return { + name: name, + age: age, + gender: gender + }; + // change code above this line +}; +console.log(createPerson("Zodiac Hasbro", 56, "male")); // returns a proper object +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions.spanish.md new file mode 100644 index 0000000000..8491d5c7e6 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions.spanish.md @@ -0,0 +1,77 @@ +--- +id: 587d7b88367417b2b2512b45 +title: Write Higher Order Arrow Functions +localeTitle: Escribir funciones de flecha de orden superior +challengeType: 1 +--- + +## Description +
    +Es hora de que veamos cuán poderosas son las funciones de flecha al procesar datos. +funciones de flecha funcionan realmente bien con funciones de orden superior, como map() , filter() y reduce() , que toman otras funciones como argumentos para procesar colecciones de datos. +Lee el siguiente código: +
    FBPosts.filter(function(post) {
      return post.thumbnail !== null && post.shares > 100 && post.likes > 500;
    })
    +Hemos escrito esto con el filter() para al menos hacerlo un poco legible. Ahora compárelo con el siguiente código que usa la sintaxis de la función de flecha en su lugar: +
    FBPosts.filter((post) => post.thumbnail !== null && post.shares > 100 && post.likes > 500)
    +Este código es más breve y realiza la misma tarea con menos líneas de código. +
    + +## Instructions +
    +Utilice la sintaxis de la función de flecha para calcular el cuadrado de solo los enteros positivos (los números decimales no son enteros) en la matriz realNumberArray y almacenar la nueva matriz en la variable squaredIntegers . +
    + +## Tests +
    + +```yml +tests: + - text: squaredIntegers debe ser una variable constante (usando const ). + testString: 'getUserInput => assert(getUserInput("index").match(/const\s+squaredIntegers/g), "squaredIntegers should be a constant variable (by using const).");' + - text: squaredIntegers debe ser una array + testString: 'assert(Array.isArray(squaredIntegers), "squaredIntegers should be an array");' + - text: ' squaredIntegers debe ser [16, 1764, 36] ' + testString: 'assert.deepStrictEqual(squaredIntegers, [16, 1764, 36], "squaredIntegers should be [16, 1764, 36]");' + - text: function palabra clave de la function no se utilizó. + testString: 'getUserInput => assert(!getUserInput("index").match(/function/g), "function keyword was not used.");' + - text: bucle no debe ser utilizado + testString: 'getUserInput => assert(!getUserInput("index").match(/(for)|(while)/g), "loop should not be used");' + - text: ' map , filter o reduce debe ser utilizado' + testString: 'getUserInput => assert(getUserInput("index").match(/map|filter|reduce/g), "map, filter, or reduce should be used");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]; +const squareList = (arr) => { + "use strict"; + // change code below this line + const squaredIntegers = arr; + // change code above this line + return squaredIntegers; +}; +// test your code +const squaredIntegers = squareList(realNumberArray); +console.log(squaredIntegers); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.spanish.md new file mode 100644 index 0000000000..e57fb21f22 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/add-elements-to-the-end-of-an-array-using-concat-instead-of-push.spanish.md @@ -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 +
    +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 concat como una forma de combinar arreglos en uno nuevo sin mutar los arreglos originales. Comparar concat con el método de push . Push agrega un elemento al final de la misma matriz a la que se llama, lo que muta esa matriz. Aquí hay un ejemplo: +
    var arr = [1, 2, 3];
    arr.push([4, 5, 6]);
    // arr is changed to [1, 2, 3, [4, 5, 6]]
    // Not the functional programming way
    +Concat ofrece una forma de agregar nuevos elementos al final de una matriz sin efectos secundarios de mutación. +
    + +## Instructions +
    +Cambie la función nonMutatingPush para que use concat para agregar newItem al final del original lugar de push . La función debe devolver una matriz. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método concat . + testString: 'assert(code.match(/\.concat/g), "Your code should use the concat method.");' + - text: Su código no debe utilizar el método de push . + testString: 'assert(!code.match(/\.push/g), "Your code should not use the push method.");' + - text: La first matriz no debe cambiar. + testString: 'assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), "The first array should not change.");' + - text: La second matriz no debe cambiar. + testString: 'assert(JSON.stringify(second) === JSON.stringify([4, 5]), "The second array should not change.");' + - text: ' nonMutatingPush([1, 2, 3], [4, 5]) debe devolver [1, 2, 3, 4, 5] .' + testString: 'assert(JSON.stringify(nonMutatingPush([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), "nonMutatingPush([1, 2, 3], [4, 5]) should return [1, 2, 3, 4, 5].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.spanish.md new file mode 100644 index 0000000000..b736cd550d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs.spanish.md @@ -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 +
    +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 reduce , 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 map y el filter son casos especiales de reduce . +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. +
    + +## Instructions +
    +Rellene la función urlSlug para que convierta un title 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 replace . 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 ( - ) +La salida debe ser todas letras minúsculas +La salida debe no tiene espacios +
    + +## Tests +
    + +```yml +tests: + - text: La variable globalTitle no debe cambiar. + testString: 'assert(globalTitle === "Winter Is Coming", "The globalTitle variable should not change.");' + - text: Su código no debe usar el método de replace para este desafío. + testString: 'assert(!code.match(/\.replace/g), "Your code should not use the replace method for this challenge.");' + - text: urlSlug("Winter Is Coming") debería devolver "winter-is-coming" . + testString: 'assert(urlSlug("Winter Is Coming") === "winter-is-coming", "urlSlug("Winter Is Coming") should return "winter-is-coming".");' + - text: urlSlug(" Winter Is Coming") debería devolver "winter-is-coming" . + testString: 'assert(urlSlug(" Winter Is Coming") === "winter-is-coming", "urlSlug(" Winter Is  Coming") should return "winter-is-coming".");' + - text: urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") "a-mind-needs-books-like-a-sword-needs-a-whetstone" urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") debería devolver "a-mind-needs-books-like-a-sword-needs-a-whetstone" . + testString: 'assert(urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") === "a-mind-needs-books-like-a-sword-needs-a-whetstone", "urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone") should return "a-mind-needs-books-like-a-sword-needs-a-whetstone".");' + - text: urlSlug("Hold The Door") debe devolver "hold-the-door" . + testString: 'assert(urlSlug("Hold The Door") === "hold-the-door", "urlSlug("Hold The Door") should return "hold-the-door".");' + +``` + +
    + +## Challenge 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" +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.spanish.md new file mode 100644 index 0000000000..1da223367c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/avoid-mutations-and-side-effects-using-functional-programming.spanish.md @@ -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 +
    +Si aún no lo ha resuelto, el problema en el desafío anterior fue con la llamada de splice en la función tabClose() . Desafortunadamente, el splice 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 splice cambió la matriz original y dio como resultado un error. +Recuerde que en la programación funcional, cambiar o alterar las cosas se denomina mutation , y el resultado se denomina side effect . Una función, idealmente, debería ser una pure function , 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. +
    + +## Instructions +
    +Rellene el código del incrementer función para que devuelva el valor de la variable global fixedValue incrementado en uno. +
    + +## Tests +
    + +```yml +tests: + - text: Su incrementer funciones no debe cambiar el valor de fixedValue . + testString: 'assert(fixedValue === 4, "Your function incrementer should not change the value of fixedValue.");' + - text: Su función incrementer debe devolver un valor que sea mayor que el valor de valor fixedValue . + testString: 'assert(newValue === 5, "Your incrementer function should return a value that is one larger than the fixedValue value.");' + +``` + +
    + +## Challenge 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 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.spanish.md new file mode 100644 index 0000000000..7f3b843ea9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-an-array-into-a-string-using-the-join-method.spanish.md @@ -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 +
    +El método de join 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: +
    var arr = ["Hello", "World"];
    var str = arr.join(" ");
    // Sets str to "Hello World"
    +
    + +## Instructions +
    +Use el método de join (entre otros) dentro de la función de sentensify para hacer una oración de las palabras en la cadena str . 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 replace . +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de join . + testString: 'assert(code.match(/\.join/g), "Your code should use the join method.");' + - text: Su código no debe utilizar el método de replace . + testString: 'assert(!code.match(/\.replace/g), "Your code should not use the replace method.");' + - text: sentensify("May-the-force-be-with-you") debe devolver una cadena. + testString: 'assert(typeof sentensify("May-the-force-be-with-you") === "string", "sentensify("May-the-force-be-with-you") should return a string.");' + - text: sentensify("May-the-force-be-with-you") debe devolver "May the force be with you" . + testString: 'assert(sentensify("May-the-force-be-with-you") === "May the force be with you", "sentensify("May-the-force-be-with-you") should return "May the force be with you".");' + - text: sentensify("The.force.is.strong.with.this.one") debe devolver "The force is strong with this one" . + testString: 'assert(sentensify("The.force.is.strong.with.this.one") === "The force is strong with this one", "sentensify("The.force.is.strong.with.this.one") should return "The force is strong with this one".");' + - text: ' sentensify("There,has,been,an,awakening") debería regresar "There has been an awakening" . + testString: 'assert(sentensify("There,has,been,an,awakening") === "There has been an awakening", "sentensify("There,has,been,an,awakening") should return "There has been an awakening".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function sentensify(str) { + // Add your code below this line + + + // Add your code above this line +} +sentensify("May-the-force-be-with-you"); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.spanish.md new file mode 100644 index 0000000000..30e09dbdab --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/combine-two-arrays-using-the-concat-method.spanish.md @@ -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 +
    +Concatenation significa unir elementos de extremo a extremo. JavaScript ofrece el método concat 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 concat , 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: +
    [1, 2, 3].concat([4, 5, 6]);
    // Returns a new array [1, 2, 3, 4, 5, 6]
    +
    + +## Instructions +
    +Utilice el método concat en la función nonMutatingConcat para concatenar attach al final del original . La función debe devolver la matriz concatenada. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método concat . + testString: 'assert(code.match(/\.concat/g), "Your code should use the concat method.");' + - text: La first matriz no debe cambiar. + testString: 'assert(JSON.stringify(first) === JSON.stringify([1, 2, 3]), "The first array should not change.");' + - text: La second matriz no debe cambiar. + testString: 'assert(JSON.stringify(second) === JSON.stringify([4, 5]), "The second array should not change.");' + - text: ' nonMutatingConcat([1, 2, 3], [4, 5]) debe devolver [1, 2, 3, 4, 5] .' + testString: 'assert(JSON.stringify(nonMutatingConcat([1, 2, 3], [4, 5])) === JSON.stringify([1, 2, 3, 4, 5]), "nonMutatingConcat([1, 2, 3], [4, 5]) should return [1, 2, 3, 4, 5].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.spanish.md new file mode 100644 index 0000000000..479c286094 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype.spanish.md @@ -0,0 +1,70 @@ +--- +id: 587d7b8f367417b2b2512b62 +title: Implement map on a Prototype +localeTitle: Implementar mapa en un prototipo +challengeType: 1 +--- + +## Description +
    +Como ha visto al aplicar Array.prototype.map() , o simplemente map() anteriormente, el método de map 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 map 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 map para intentar implementar una versión que se comporte exactamente como Array.prototype.map() con un bucle for o Array.prototype.forEach() . +Nota: Una función pura puede alterar las variables locales definidas dentro de su alcance, aunque es preferible evitar eso también. +
    + +## Instructions +
    +Escriba su propio Array.prototype.myMap() , que debería comportarse exactamente como Array.prototype.map() . Puedes usar un bucle for o el método forEach . +
    + +## Tests +
    + +```yml +tests: + - text: ' new_s debe ser igual a [46, 130, 196, 10] .' + testString: 'assert(JSON.stringify(new_s) === JSON.stringify([46, 130, 196, 10]), "new_s should equal [46, 130, 196, 10].");' + - text: Su código no debe utilizar el método de map . + testString: 'assert(!code.match(/\.map/g), "Your code should not use the map method.");' + +``` + +
    + +## Challenge 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; +}); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.spanish.md new file mode 100644 index 0000000000..cc07b6e618 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype.spanish.md @@ -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 +
    +Nos enseñaría mucho sobre el método de filter si intentáramos implementar una versión que se comporte exactamente como Array.prototype.filter() . Puede usar un bucle for o Array.prototype.forEach() . +Nota: Una función pura puede alterar las variables locales definidas dentro de su alcance, aunque es preferible evitar eso también. +
    + +## Instructions +
    +Escriba su propio Array.prototype.myFilter() , que debe comportarse exactamente como Array.prototype.filter() . Puede usar un bucle for o el método Array.prototype.forEach() . +
    + +## Tests +
    + +```yml +tests: + - text: ' new_s debe ser igual a [23, 65, 5] .' + testString: 'assert(JSON.stringify(new_s) === JSON.stringify([23, 65, 5]), "new_s should equal [23, 65, 5].");' + - text: Su código no debe utilizar el método de filter . + testString: 'assert(!code.match(/\.filter/g), "Your code should not use the filter method.");' + +``` + +
    + +## Challenge 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; +}); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.spanish.md new file mode 100644 index 0000000000..9e5038e4ef --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/introduction-to-currying-and-partial-application.spanish.md @@ -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 +
    +La arity de una función es el número de argumentos que requiere. Currying una función significa convertir una función de N arity en N funciones de arity 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: +
    //Un-curried function
    function unCurried(x, y) {
      return x + y;
    }

    //Curried function
    function curried(x) {
      return function(y) {
        return x + y;
      }
    }
    curried(1)(2) // Returns 3
    +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 curried en el ejemplo anterior: +
    // Call a curried function in parts:
    var funcForY = curried(1);
    console.log(funcForY(2)); // Prints 3
    +De manera similar, partial application 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: +
    //Impartial function
    function impartial(x, y, z) {
      return x + y + z;
    }
    var partialFn = impartial.bind(this, 1, 2);
    partialFn(10); // Returns 13
    +
    + +## Instructions +
    +Rellene el cuerpo de la función de add para que use el curry para agregar los parámetros x , y y z . +
    + +## Tests +
    + +```yml +tests: + - text: add(10)(20)(30) debe devolver 60 . + testString: 'assert(add(10)(20)(30) === 60, "add(10)(20)(30) should return 60.");' + - text: add(1)(2)(3) debe devolver 6 . + testString: 'assert(add(1)(2)(3) === 6, "add(1)(2)(3) should return 6.");' + - text: add(11)(22)(33) debe devolver 66 . + testString: 'assert(add(11)(22)(33) === 66, "add(11)(22)(33) should return 66.");' + - text: Su código debe incluir una declaración final que devuelva x + y + z . + testString: 'assert(code.match(/[xyz]\s*?\+\s*?[xyz]\s*?\+\s*?[xyz]/g), "Your code should include a final statement that returns x + y + z.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function add(x) { + // Add your code below this line + + + // Add your code above this line +} +add(10)(20)(30); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.spanish.md new file mode 100644 index 0000000000..b9654a86f1 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/learn-about-functional-programming.spanish.md @@ -0,0 +1,87 @@ +--- +id: 587d7b8d367417b2b2512b5b +title: Learn About Functional Programming +localeTitle: Aprenda acerca de la programación funcional +challengeType: 1 +--- + +## 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. +INPUT -> PROCESS -> OUTPUT +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 +
    + +## Instructions +
    +A los miembros de freeCodeCamp les encanta el té. +En el editor de código, las funciones prepareTea y getTea ya están definidas para usted. Llame a la función getTea para obtener 40 tazas de té para el equipo y guárdelas en la variable tea4TeamFCC . +
    + +## Tests +
    + +```yml +tests: + - text: La variable tea4TeamFCC debe contener 40 tazas de té para el equipo. + testString: 'assert(tea4TeamFCC.length === 40, "The tea4TeamFCC variable should hold 40 cups of tea for the team.");' + - text: La variable tea4TeamFCC debe contener tazas de té verde. + testString: 'assert(tea4TeamFCC[0] === "greenTea", "The tea4TeamFCC variable should hold cups of green tea.");' + +``` + +
    + +## Challenge 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} 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.spanish.md new file mode 100644 index 0000000000..7a8c8b2a51 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/pass-arguments-to-avoid-external-dependence-in-a-function.spanish.md @@ -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 +
    +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 incrementer la función no funcionaría sin que la variable global fixedValue 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. +
    + +## Instructions +
    +Actualicemos la función incrementer para declarar claramente sus dependencias. +Escriba la función incrementer para que tome un argumento y luego aumente el valor en uno. +
    + +## Tests +
    + +```yml +tests: + - text: Su incrementer funciones no debe cambiar el valor de fixedValue . + testString: 'assert(fixedValue === 4, "Your function incrementer should not change the value of fixedValue.");' + - text: Su función incrementer debe tomar un parámetro. + testString: 'assert(code.match(/function\s+?incrementer\s*?\(.+?\)/g), "Your incrementer function should take a parameter.");' + - text: Su función incrementer debe devolver un valor que sea mayor que el valor de valor fixedValue . + testString: 'assert(newValue === 5, "Your incrementer function should return a value that is one larger than the fixedValue value.");' + +``` + +
    + +## Challenge 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 +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.spanish.md new file mode 100644 index 0000000000..e3b80682fe --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions.spanish.md @@ -0,0 +1,91 @@ +--- +id: 587d7b8f367417b2b2512b60 +title: Refactor Global Variables Out of Functions +localeTitle: Refactorizar variables globales fuera de funciones +challengeType: 1 +--- + +## 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. +
    + +## Instructions +
    +Refactorice (reescriba) el código para que la matriz de bookList global no se bookList dentro de ninguna de las funciones. La función de add debería agregar el bookName de bookName dado al final de una matriz. La función de remove debe eliminar el bookName de bookName dado de una matriz. Ambas funciones deben devolver una matriz, y cualquier parámetro nuevo debe agregarse antes del bookName one. +
    + +## Tests +
    + +```yml +tests: + - text: ' bookList no debe cambiar y aún debe ser igual a ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] .' + testString: 'assert(JSON.stringify(bookList) === JSON.stringify(["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]), "bookList should not change and still equal ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"].");' + - text: ' newBookList debería ser igual a ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"] .' + 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"]), "newBookList should equal ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"].");' + - text: ' newerBookList debería ser igual a ["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"] .' + testString: 'assert(JSON.stringify(newerBookList) === JSON.stringify(["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]), "newerBookList should equal ["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"].");' + - text: ' newestBookList debería ser igual a ["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"] . + testString: 'assert(JSON.stringify(newestBookList) === JSON.stringify(["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]), "newestBookList should equal ["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.spanish.md new file mode 100644 index 0000000000..73dcbfbc6f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/remove-elements-from-an-array-using-slice-instead-of-splice.spanish.md @@ -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 +
    +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 splice 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 splice muta la matriz original a la que se llama. Aquí hay un ejemplo: +
    var cities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
    cities.splice(3, 1); // Returns "London" and deletes it from the cities array
    // cities is now ["Chicago", "Delhi", "Islamabad", "Berlin"]
    +Como hemos visto en el último desafío, la slice método no muta la matriz original, pero devuelve una nueva que se pueden guardar en una variable. Recuerde que el método de slice 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 slice método en lugar de splice ayuda a evitar los efectos secundarios de matriz-mutación. +
    + +## Instructions +
    +Reescriba la función nonMutatingSplice utilizando slice lugar de splice . Debe limitar la matriz de cities 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. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de slice . + testString: 'assert(code.match(/\.slice/g), "Your code should use the slice method.");' + - text: Su código no debe utilizar el método de splice . + testString: 'assert(!code.match(/\.splice/g), "Your code should not use the splice method.");' + - text: La matriz inputCities no debería cambiar. + testString: 'assert(JSON.stringify(inputCities) === JSON.stringify(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]), "The inputCities array should not change.");' + - text: ' nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]) debe devolver ["Chicago", "Delhi", "Islamabad"] .' + testString: 'assert(JSON.stringify(nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"])) === JSON.stringify(["Chicago", "Delhi", "Islamabad"]), "nonMutatingSplice(["Chicago", "Delhi", "Islamabad", "London", "Berlin"]) should return ["Chicago", "Delhi", "Islamabad"].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.spanish.md new file mode 100644 index 0000000000..0b71bea524 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-a-sorted-array-without-changing-the-original-array.spanish.md @@ -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 +
    +Un efecto secundario del método de sort 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 concat devuelve una nueva matriz), luego ejecute el método de sort . +
    + +## Instructions +
    +Utilice el método de sort en la función nonMutatingSort para ordenar los elementos de una matriz en orden ascendente. La función debe devolver una nueva matriz y no mutar la variable globalArray . +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de sort . + testString: 'assert(code.match(/\.sort/g), "Your code should use the sort method.");' + - text: Su código debe utilizar el método concat . + testString: 'assert(code.match(/\.concat/g), "Your code should use the concat method.");' + - text: La variable globalArray no debe cambiar. + testString: 'assert(JSON.stringify(globalArray) === JSON.stringify([5, 6, 3, 2, 9]), "The globalArray variable should not change.");' + - text: ' nonMutatingSort(globalArray) debe devolver [2, 3, 5, 6, 9] .' + testString: 'assert(JSON.stringify(nonMutatingSort(globalArray)) === JSON.stringify([2, 3, 5, 6, 9]), "nonMutatingSort(globalArray) should return [2, 3, 5, 6, 9].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.spanish.md new file mode 100644 index 0000000000..c0025fca50 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/return-part-of-an-array-using-the-slice-method.spanish.md @@ -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 +
    +El método de slice 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 slice método no muta la matriz original, pero devuelve una nueva. +Aquí hay un ejemplo: +
    var arr = ["Cat", "Dog", "Tiger", "Zebra"];
    var newArray = arr.slice(1, 3);
    // Sets newArray to ["Dog", "Tiger"]
    +
    + +## Instructions +
    +Utilice la slice método en el sliceArray función para devolver parte de la anim matriz dada las proporcionadas beginSlice y endSlice índices. La función debe devolver una matriz. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de slice . + testString: 'assert(code.match(/\.slice/g), "Your code should use the slice method.");' + - text: La variable inputAnim no debe cambiar. + testString: 'assert(JSON.stringify(inputAnim) === JSON.stringify(["Cat", "Dog", "Tiger", "Zebra", "Ant"]), "The inputAnim variable should not change.");' + - text: ' sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3) debe devolver ["Dog", "Tiger"] .' + testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3)) === JSON.stringify(["Dog", "Tiger"]), "sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 3) should return ["Dog", "Tiger"].");' + - text: ' sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1) debe devolver ["Cat"] .' + testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1)) === JSON.stringify(["Cat"]), "sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 0, 1) should return ["Cat"].");' + - text: ' sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4) debe devolver ["Dog", "Tiger", "Zebra"] .' + testString: 'assert(JSON.stringify(sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4)) === JSON.stringify(["Dog", "Tiger", "Zebra"]), "sliceArray(["Cat", "Dog", "Tiger", "Zebra", "Ant"], 1, 4) should return ["Dog", "Tiger", "Zebra"].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.spanish.md new file mode 100644 index 0000000000..d672cdae9b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method.spanish.md @@ -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 +
    +El método de sort ordena los elementos de una matriz de acuerdo con la función de devolución de llamada. +Por ejemplo: +
    function ascendingOrder(arr) {
      return arr.sort(function(a, b) {
        return a - b;
      });
    }
    ascendingOrder([1, 5, 2, 3, 4]);
    // Returns [1, 2, 3, 4, 5]

    function reverseAlpha(arr) {
      return arr.sort(function(a, b) {
        return a < b;
      });
    }
    reverseAlpha(['l', 'h', 'z', 'b', 's']);
    // Returns ['z', 's', 'l', 'h', 'b']
    +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. +
    + +## Instructions +
    +Utilice el método de sort en la función de orden alphabeticalOrder para ordenar los elementos de arr en orden alfabético. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de sort . + testString: 'assert(code.match(/\.sort/g), "Your code should use the sort method.");' + - text: ' alphabeticalOrder(["a", "d", "c", "a", "z", "g"]) debe devolver ["a", "a", "c", "d", "g", "z"] . ' + testString: 'assert(JSON.stringify(alphabeticalOrder(["a", "d", "c", "a", "z", "g"])) === JSON.stringify(["a", "a", "c", "d", "g", "z"]), "alphabeticalOrder(["a", "d", "c", "a", "z", "g"]) should return ["a", "a", "c", "d", "g", "z"].");' + - text: ' alphabeticalOrder(["x", "h", "a", "m", "n", "m"]) debe devolver ["a", "h", "m", "m", "n", "x"] . ' + testString: 'assert(JSON.stringify(alphabeticalOrder(["x", "h", "a", "m", "n", "m"])) === JSON.stringify(["a", "h", "m", "m", "n", "x"]), "alphabeticalOrder(["x", "h", "a", "m", "n", "m"]) should return ["a", "h", "m", "m", "n", "x"].");' + - text: ' alphabeticalOrder(["a", "a", "a", "a", "x", "t"]) debe devolver ["a", "a", "a", "a", "t", "x"] . ' + testString: 'assert(JSON.stringify(alphabeticalOrder(["a", "a", "a", "a", "x", "t"])) === JSON.stringify(["a", "a", "a", "a", "t", "x"]), "alphabeticalOrder(["a", "a", "a", "a", "x", "t"]) should return ["a", "a", "a", "a", "t", "x"].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function alphabeticalOrder(arr) { + // Add your code below this line + + + // Add your code above this line +} +alphabeticalOrder(["a", "d", "c", "a", "z", "g"]); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.spanish.md new file mode 100644 index 0000000000..b67a3b87ed --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/split-a-string-into-an-array-using-the-split-method.spanish.md @@ -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 +
    +El método de split 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: +
    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"]
    +Dado que las cadenas son inmutables, el método de split facilita el trabajo con ellas. +
    + +## Instructions +
    +Utilice la split método dentro de la splitify función de dividir str 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. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar el método de split . + testString: 'assert(code.match(/\.split/g), "Your code should use the split method.");' + - text: ' splitify("Hello World,I-am code") debe devolver ["Hello", "World", "I", "am", "code"] .' + testString: 'assert(JSON.stringify(splitify("Hello World,I-am code")) === JSON.stringify(["Hello", "World", "I", "am", "code"]), "splitify("Hello World,I-am code") should return ["Hello", "World", "I", "am", "code"].");' + - text: ' splitify("Earth-is-our home") debería devolver ["Earth", "is", "our", "home"] .' + testString: 'assert(JSON.stringify(splitify("Earth-is-our home")) === JSON.stringify(["Earth", "is", "our", "home"]), "splitify("Earth-is-our home") should return ["Earth", "is", "our", "home"].");' + - text: ' splitify("This.is.a-sentence") debe devolver ["This", "is", "a", "sentence"] .' + testString: 'assert(JSON.stringify(splitify("This.is.a-sentence")) === JSON.stringify(["This", "is", "a", "sentence"]), "splitify("This.is.a-sentence") should return ["This", "is", "a", "sentence"].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function splitify(str) { + // Add your code below this line + + + // Add your code above this line +} +splitify("Hello World,I-am code"); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.spanish.md new file mode 100644 index 0000000000..7a4d1bd45c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-functional-programming-terminology.spanish.md @@ -0,0 +1,103 @@ +--- +id: 587d7b8e367417b2b2512b5c +title: Understand Functional Programming Terminology +localeTitle: Entender la terminología de programación funcional +challengeType: 1 +--- + +## 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 getTea del último desafío para manejar varias solicitudes de té. Podemos modificar getTea para aceptar una función como parámetro para 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 cambian las solicitudes de los clientes. +Pero primero, vamos a cubrir algunos términos funcionales: +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 los haya visto pasar a otros métodos, por ejemplo, en el filter , 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 first class . En JavaScript, todas las funciones son funciones de first class . +Las funciones que toman una función como argumento o que devuelven una función como valor de retorno se denominan funciones de higher order . +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 lambda . +
    + +## Instructions +
    +Prepare 27 tazas de té verde y 13 tazas de té negro y almacénelas en las variables tea4GreenTeamFCC y tea4BlackTeamFCC , respectivamente. Tenga en cuenta que la función getTea 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. +
    + +## Tests +
    + +```yml +tests: + - text: La variable tea4GreenTeamFCC debe contener 27 tazas de té verde para el equipo. + testString: 'assert(tea4GreenTeamFCC.length === 27, "The tea4GreenTeamFCC variable should hold 27 cups of green tea for the team.");' + - text: La variable tea4GreenTeamFCC debe contener tazas de té verde. + testString: 'assert(tea4GreenTeamFCC[0] === "greenTea", "The tea4GreenTeamFCC variable should hold cups of green tea.");' + - text: La variable tea4BlackTeamFCC debe contener 13 tazas de té negro. + testString: 'assert(tea4BlackTeamFCC.length === 13, "The tea4BlackTeamFCC variable should hold 13 cups of black tea.");' + - text: La variable tea4BlackTeamFCC debe contener tazas de té negro. + testString: 'assert(tea4BlackTeamFCC[0] === "blackTea", "The tea4BlackTeamFCC variable should hold cups of black tea.");' + +``` + +
    + +## Challenge 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} 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 +); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.spanish.md new file mode 100644 index 0000000000..c91062fb8f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/understand-the-hazards-of-using-imperative-code.spanish.md @@ -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 +
    +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 for 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 for mencionado anteriormente, puede llamar al método de map 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 tabOpen() , tabClose() y join() . Las tabs matriz forman parte del objeto Window que almacena el nombre de las páginas abiertas. +

    Instrucciones

    +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 ['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium', 'new tab', 'Netflix', 'YouTube', 'Vine', 'GMail', 'Work mail', 'Docs', 'freeCodeCamp', 'new tab'] 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. +

    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Avanza para entender el error. + testString: 'assert(true, "Move ahead to understand the error.");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.spanish.md new file mode 100644 index 0000000000..627d471ddf --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-every-method-to-check-that-every-element-in-an-array-meets-a-criteria.spanish.md @@ -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 +
    +every métodos funcionan con matrices para verificar si cada elemento pasa una prueba en particular. Devuelve un valor booleano: true si todos los valores cumplen los criterios, false si no. +Por ejemplo, el siguiente código verificará si cada elemento de la matriz de numbers es menor que 10: +
    var numbers = [1, 5, 8, 0, 10, 11];
    numbers.every(function(currentValue) {
      return currentValue < 10;
    });
    // Returns false
    +
    + +## Instructions +
    +Use every método dentro de la función checkPositive para verificar si cada elemento en arr es positivo. La función debe devolver un valor booleano. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar every métodos. + testString: 'assert(code.match(/\.every/g), "Your code should use the every method.");' + - text: ' checkPositive([1, 2, 3, -4, 5]) debe devolver false .' + testString: 'assert(!checkPositive([1, 2, 3, -4, 5]), "checkPositive([1, 2, 3, -4, 5]) should return false.");' + - text: ' checkPositive([1, 2, 3, 4, 5]) debe devolver true .' + testString: 'assert(checkPositive([1, 2, 3, 4, 5]), "checkPositive([1, 2, 3, 4, 5]) should return true.");' + - text: ' checkPositive([1, -2, 3, -4, 5]) debe devolver false .' + testString: 'assert(!checkPositive([1, -2, 3, -4, 5]), "checkPositive([1, -2, 3, -4, 5]) should return false.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function checkPositive(arr) { + // Add your code below this line + + + // Add your code above this line +} +checkPositive([1, 2, 3, -4, 5]); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.spanish.md new file mode 100644 index 0000000000..ff49d26898 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-filter-method-to-extract-data-from-an-array.spanish.md @@ -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 +
    +Otra función de matriz útil es Array.prototype.filter() , o simplemente filter() . El método de filter devuelve una nueva matriz que es a lo sumo tan larga como la matriz original, pero generalmente tiene menos elementos. +Filter no altera la matriz original, al igual que el map . 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. +
    + +## Instructions +
    +La variable watchList contiene una serie de objetos con información sobre varias películas. Use una combinación de filter y map para devolver una nueva matriz de objetos con solo title y claves de rating , pero donde imdbRating 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. +
    + +## Tests +
    + +```yml +tests: + - text: La variable watchList no debe cambiar. + testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The watchList variable should not change.");' + - text: Su código debe utilizar el método de filter . + testString: 'assert(code.match(/\.filter/g), "Your code should use the filter method.");' + - text: Su código no debe utilizar un bucle for . + testString: 'assert(!code.match(/for\s*?\(.+?\)/g), "Your code should not use a for loop.");' + - text: ' 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"}] . ' + 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"}], "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"}].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.spanish.md new file mode 100644 index 0000000000..547f30b772 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-map-method-to-extract-data-from-an-array.spanish.md @@ -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 +
    +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 First Class Objects 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 Array.prototype.map() , o más simplemente un map . +Recuerde que el método de map 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. +
    + +## Instructions +
    +La matriz watchList contiene objetos con información sobre varias películas. Use el map para extraer el título y la clasificación de la watchList de watchList y guarde la nueva matriz en la variable de rating . El código en el editor actualmente usa un bucle for para hacer esto, reemplaza la funcionalidad de bucle con tu expresión de map . +
    + +## Tests +
    + +```yml +tests: + - text: La variable watchList no debe cambiar. + testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The watchList variable should not change.");' + - text: Su código no debe utilizar un bucle for . + testString: 'assert(!code.match(/for\s*?\(.+?\)/g), "Your code should not use a for loop.");' + - text: Su código debe utilizar el método de map . + testString: 'assert(code.match(/\.map/g), "Your code should use the map method.");' + - text: La rating debería 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"}] . ' + 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"}]), "rating 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"}].");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.spanish.md new file mode 100644 index 0000000000..86068991ad --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.spanish.md @@ -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 +
    +Array.prototype.reduce() , o simplemente reduce() , 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 reduce . +Este no es el caso con los métodos de filter y map , 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 filter o el map no podrían procesarlo. +El método de reduce permite formas más generales de procesamiento de matrices, y es posible mostrar que tanto el filter como el map pueden derivarse como una aplicación especial de reduce . +Sin embargo, antes de que lleguemos allí, practiquemos reduce primero. +
    + +## Instructions +
    +La variable watchList contiene una serie de objetos con información sobre varias películas. Use reduce para encontrar la calificación promedio de IMDB de las películas dirigidas por Christopher Nolan . Recuerde de los desafíos anteriores cómo filter datos y map para obtener lo que necesita. Es posible que deba crear otras variables, pero guardar el promedio final en la variable averageRating . 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. +
    + +## Tests +
    + +```yml +tests: + - text: La variable watchList no debe cambiar. + testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The watchList variable should not change.");' + - text: Su código debe utilizar el método de reduce . + testString: 'assert(code.match(/\.reduce/g), "Your code should use the reduce method.");' + - text: La averageRating debe ser igual a 8.675. + testString: 'assert(averageRating == 8.675, "The averageRating should equal 8.675.");' + - text: Su código no debe utilizar un bucle for . + testString: 'assert(!code.match(/for\s*?\(.*\)/g), "Your code should not use a for loop.");' + +``` + +
    + +## Challenge 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); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.spanish.md new file mode 100644 index 0000000000..daf6635801 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/functional-programming/use-the-some-method-to-check-that-any-elements-in-an-array-meet-a-criteria.spanish.md @@ -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 +
    +El some método funciona con matrices para comprobar si cualquier elemento pasa una prueba particular. Devuelve un valor booleano: true si alguno de los valores cumple los criterios, false si no. +Por ejemplo, el siguiente código verificará si algún elemento de la matriz de numbers es menor que 10: +
    var numbers = [10, 50, 8, 220, 110, 11];
    numbers.some(function(currentValue) {
      return currentValue < 10;
    });
    // Returns true
    +
    + +## Instructions +
    +Use some método dentro de la función checkPositive para verificar si algún elemento en arr es positivo. La función debe devolver un valor booleano. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe utilizar some método. + testString: 'assert(code.match(/\.some/g), "Your code should use the some method.");' + - text: ' checkPositive([1, 2, 3, -4, 5]) debe devolver true .' + testString: 'assert(checkPositive([1, 2, 3, -4, 5]), "checkPositive([1, 2, 3, -4, 5]) should return true.");' + - text: ' checkPositive([1, 2, 3, 4, 5]) debe devolver true .' + testString: 'assert(checkPositive([1, 2, 3, 4, 5]), "checkPositive([1, 2, 3, 4, 5]) should return true.");' + - text: ' checkPositive([-1, -2, -3, -4, -5]) debe devolver false .' + testString: 'assert(!checkPositive([-1, -2, -3, -4, -5]), "checkPositive([-1, -2, -3, -4, -5]) should return false.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function checkPositive(arr) { + // Add your code below this line + + + // Add your code above this line +} +checkPositive([1, 2, 3, -4, 5]); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.spanish.md new file mode 100644 index 0000000000..fbdc640012 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional.spanish.md @@ -0,0 +1,85 @@ +--- +id: a97fd23d9b809dac9921074f +title: Arguments Optional +localeTitle: Argumentos Opcionales +isRequired: true +challengeType: 5 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/arguments-optional' +--- + +## Description +
    +Crea una función que suma dos argumentos juntos. Si solo se proporciona un argumento, entonces devuelva una función que espere un argumento y devuelva la suma. +Por ejemplo, addTogether(2, 3) debe devolver 5 y addTogether(2) debe devolver una función. +llamar a esta función devuelta con un solo argumento, se devolverá la suma: +var sumTwoAnd = addTogether(2); +sumTwoAnd(3) devuelve 5 . +Si cualquiera de los argumentos no es un número válido, devuelva indefinido. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' addTogether(2, 3) debe devolver 5.' + testString: 'assert.deepEqual(addTogether(2, 3), 5, "addTogether(2, 3) should return 5.");' + - text: addTogether(2)(3) debe devolver 5. + testString: 'assert.deepEqual(addTogether(2)(3), 5, "addTogether(2)(3) should return 5.");' + - text: ' addTogether("http://bit.ly/IqT6zt") debe devolver undefined.' + testString: 'assert.isUndefined(addTogether("http://bit.ly/IqT6zt"), "addTogether("http://bit.ly/IqT6zt") should return undefined.");' + - text: ' addTogether(2, "3") debe devolver indefinido.' + testString: 'assert.isUndefined(addTogether(2, "3"), "addTogether(2, "3") should return undefined.");' + - text: ' addTogether(2)([3]) debe devolver indefinido.' + testString: 'assert.isUndefined(addTogether(2)([3]), "addTogether(2)([3]) should return undefined.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function addTogether() { + return false; +} + +addTogether(2,3); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function addTogether() { + var a = arguments[0]; + if (toString.call(a) !== '[object Number]') return; + if (arguments.length === 1) { + return function(b) { + if (toString.call(b) !== '[object Number]') return; + return a + b; + }; + } + var b = arguments[1]; + if (toString.call(b) !== '[object Number]') return; + return a + arguments[1]; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.spanish.md new file mode 100644 index 0000000000..ac576710cb --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents.spanish.md @@ -0,0 +1,64 @@ +--- +id: a8d97bd4c764e91f9d2bda01 +title: Binary Agents +localeTitle: Agentes binarios +isRequired: true +challengeType: 5 +--- + +## Description +
    +Devuelve una frase traducida al inglés de la cadena binaria pasada. +La cadena binaria estará separada por espacios. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111") ' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '. + testString: 'assert.deepEqual(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"), "Aren"t bonfires fun!?", "binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111") should return "Aren't bonfires fun!?"");' + - text: binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001") 0011. + testString: 'assert.deepEqual(binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001"), "I love FreeCodeCamp!", "binaryAgent("01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 01100100 01100101 01000011 01100001 01101101 01110000 00100001") should return "I love FreeCodeCamp!"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function binaryAgent(str) { + return str; +} + +binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function binaryAgent(str) { + return str.split(' ').map(function(s) { return parseInt(s, 2); }).map(function(b) { return String.fromCharCode(b);}).join(''); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.spanish.md new file mode 100644 index 0000000000..84ec677d66 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities.spanish.md @@ -0,0 +1,82 @@ +--- +id: a6b0bb188d873cb2c8729495 +title: Convert HTML Entities +localeTitle: Convertir entidades HTML +isRequired: true +challengeType: 5 +--- + +## Description +
    +Convierta los caracteres & , < , > , " (comillas dobles) y ' (apóstrofe), en una cadena a sus entidades HTML correspondientes. +Recuerde usar Lectura-Búsqueda-Preguntar si se atasca. Intente vincular el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' convertHTML("Dolce & Gabbana") debe devolver Dolce &​amp; Gabbana . + testString: 'assert.match(convertHTML("Dolce & Gabbana"), /Dolce & Gabbana/, "convertHTML("Dolce & Gabbana") should return Dolce &​amp; Gabbana.");' + - text: ' convertHTML("Hamburgers < Pizza < Tacos") debe devolver Hamburgers &​lt; Pizza &​lt; Tacos . + testString: 'assert.match(convertHTML("Hamburgers < Pizza < Tacos"), /Hamburgers < Pizza < Tacos/, "convertHTML("Hamburgers < Pizza < Tacos") should return Hamburgers &​lt; Pizza &​lt; Tacos.");' + - text: ' convertHTML("Sixty > twelve") debe devolver Sixty &​gt; twelve . + testString: 'assert.match(convertHTML("Sixty > twelve"), /Sixty > twelve/, "convertHTML("Sixty > twelve") should return Sixty &​gt; twelve.");' + - text: ' convertHTML('Stuff in "quotation marks"') debería devolver Stuff in &​quot;quotation marks&​quot; . + testString: 'assert.match(convertHTML("Stuff in "quotation marks""), /Stuff in "quotation marks"/, "convertHTML('Stuff in "quotation marks"') should return Stuff in &​quot;quotation marks&​quot;.");' + - text: ' convertHTML("Schindler's List") debe devolver la Schindler&​apos;s List . + testString: 'assert.match(convertHTML("Schindler"s List"), /Schindler's List/, "convertHTML("Schindler's List") should return Schindler&​apos;s List.");' + - text: ' convertHTML("<>") debe devolver &​lt;&​gt; . + testString: 'assert.match(convertHTML("<>"), /<>/, "convertHTML("<>") should return &​lt;&​gt;.");' + - text: convertHTML("abc") debe devolver abc . + testString: 'assert.strictEqual(convertHTML("abc"), "abc", "convertHTML("abc") should return abc.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function convertHTML(str) { + // :) + return str; +} + +convertHTML("Dolce & Gabbana"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var MAP = { '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": '''}; + +function convertHTML(str) { + return str.replace(/[&<>"']/g, function(c) { + return MAP[c]; + }); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.spanish.md new file mode 100644 index 0000000000..c7ee07d6a0 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays.spanish.md @@ -0,0 +1,110 @@ +--- +id: a5de63ebea8dbee56860f4f2 +title: Diff Two Arrays +localeTitle: Diferencia dos matrices +isRequired: true +challengeType: 5 +--- + +## Description +
    +Compare dos arreglos y devuelva un nuevo arreglo con los elementos que solo se encuentran en uno de los dos arreglos dados, pero no en ambos. En otras palabras, devuelva la diferencia simétrica de las dos matrices. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +Nota
    Puede devolver la matriz con sus elementos en cualquier orden. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) debe devolver una matriz.' + testString: 'assert(typeof diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) === "object", "diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) should return an array.");' + - text: ' ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] debe devolver ["pink wool"] . ' + testString: 'assert.sameMembers(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]), ["pink wool"], "["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["pink wool"].");' + - text: ' ["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] debería devolver una matriz con un elemento '. + testString: 'assert(diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]).length === 1, "["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with one item.");' + - text: ' ["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] debe devolver ["diorite", "pink wool"] . + testString: 'assert.sameMembers(diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]), ["diorite", "pink wool"], "["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return ["diorite", "pink wool"].");' + - text: ' ["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] debe devolver una matriz con dos elementos. + testString: 'assert(diffArray(["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]).length === 2, "["andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"] should return an array with two items.");' + - text: ' ["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] debe devolver [] .' + testString: 'assert.sameMembers(diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]), [], "["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return [].");' + - text: ' ["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] debe devolver una matriz vacía.' + testString: 'assert(diffArray(["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"]).length === 0, "["andesite", "grass", "dirt", "dead shrub"], ["andesite", "grass", "dirt", "dead shrub"] should return an empty array.");' + - text: ' [1, 2, 3, 5], [1, 2, 3, 4, 5] debe devolver [4] .' + testString: 'assert.sameMembers(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), [4], "[1, 2, 3, 5], [1, 2, 3, 4, 5] should return [4].");' + - text: ' [1, 2, 3, 5], [1, 2, 3, 4, 5] debe devolver una matriz con un elemento.' + testString: 'assert(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]).length === 1, "[1, 2, 3, 5], [1, 2, 3, 4, 5] should return an array with one item.");' + - text: ' [1, "calf", 3, "piglet"], [1, "calf", 3, 4] debe devolver ["piglet", 4] .' + testString: 'assert.sameMembers(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]), ["piglet", 4], "[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return ["piglet", 4].");' + - text: ' [1, "calf", 3, "piglet"], [1, "calf", 3, 4] debe devolver una matriz con dos elementos.' + testString: 'assert(diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]).length === 2, "[1, "calf", 3, "piglet"], [1, "calf", 3, 4] should return an array with two items.");' + - text: ' [], ["snuffleupagus", "cookie monster", "elmo"] debe devolver ["snuffleupagus", "cookie monster", "elmo"] .' + testString: 'assert.sameMembers(diffArray([], ["snuffleupagus", "cookie monster", "elmo"]), ["snuffleupagus", "cookie monster", "elmo"], "[], ["snuffleupagus", "cookie monster", "elmo"] should return ["snuffleupagus", "cookie monster", "elmo"].");' + - text: ' [], ["snuffleupagus", "cookie monster", "elmo"] debe devolver una matriz con tres elementos.' + testString: 'assert(diffArray([], ["snuffleupagus", "cookie monster", "elmo"]).length === 3, "[], ["snuffleupagus", "cookie monster", "elmo"] should return an array with three items.");' + - text: ' [1, "calf", 3, "piglet"], [7, "filly"] debe devolver [1, "calf", 3, "piglet", 7, "filly"] .' + testString: 'assert.sameMembers(diffArray([1, "calf", 3, "piglet"], [7, "filly"]), [1, "calf", 3, "piglet", 7, "filly"], "[1, "calf", 3, "piglet"], [7, "filly"] should return [1, "calf", 3, "piglet", 7, "filly"].");' + - text: ' [1, "calf", 3, "piglet"], [7, "filly"] debe devolver una matriz con seis elementos.' + testString: 'assert(diffArray([1, "calf", 3, "piglet"], [7, "filly"]).length === 6, "[1, "calf", 3, "piglet"], [7, "filly"] should return an array with six items.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function diffArray(arr1, arr2) { + var newArr = []; + // Same, same; but different. + return newArr; +} + +diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function diffArray(arr1, arr2) { + var newArr = []; + var h1 = Object.create(null); + arr1.forEach(function(e) { + h1[e] = e; + }); + + var h2 = Object.create(null); + arr2.forEach(function(e) { + h2[e] = e; + }); + + Object.keys(h1).forEach(function(e) { + if (!(e in h2)) newArr.push(h1[e]); + }); + Object.keys(h2).forEach(function(e) { + if (!(e in h1)) newArr.push(h2[e]); + }); + // Same, same; but different. + return newArr; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.spanish.md new file mode 100644 index 0000000000..6266e808bd --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing.spanish.md @@ -0,0 +1,75 @@ +--- +id: afd15382cdfb22c9efe8b7de +title: DNA Pairing +localeTitle: Apareamiento de ADN +isRequired: true +challengeType: 5 +--- + +## Description +
    +A la cadena de ADN le falta el elemento de emparejamiento. Tome cada carácter, obtenga su par y devuelva los resultados como una matriz 2d. +pares de bases son un par de AT y CG. Empareja el elemento que falta con el carácter proporcionado. +Devuelve el carácter proporcionado como el primer elemento en cada matriz. +Por ejemplo, para la entrada GCG, devuelva [["G", "C"], ["C", "G"], ["G", "C"]] +El carácter y su par están emparejados en una matriz, y todas las matrices se agrupan en una matriz de encapsulación. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' pairElement("ATCGA") debe devolver [["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]] . ' + testString: 'assert.deepEqual(pairElement("ATCGA"),[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]], "pairElement("ATCGA") should return [["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]].");' + - text: ' pairElement("TTGAG") debe devolver [["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]] . ' + testString: 'assert.deepEqual(pairElement("TTGAG"),[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]], "pairElement("TTGAG") should return [["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]].");' + - text: ' pairElement("CTCTA") debe devolver [["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]] . ' + testString: 'assert.deepEqual(pairElement("CTCTA"),[["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]], "pairElement("CTCTA") should return [["C","G"],["T","A"],["C","G"],["T","A"],["A","T"]].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function pairElement(str) { + return str; +} + +pairElement("GCG"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var lookup = Object.create(null); +lookup.A = 'T'; +lookup.T = 'A'; +lookup.C = 'G'; +lookup.G = 'C'; + +function pairElement(str) { + return str.split('').map(function(p) {return [p, lookup[p]];}); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.spanish.md new file mode 100644 index 0000000000..cf2f9c1c09 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it.spanish.md @@ -0,0 +1,77 @@ +--- +id: a5deed1811a43193f9f1c841 +title: Drop it +localeTitle: Déjalo caer +isRequired: true +challengeType: 5 +--- + +## Description +
    +Dado la matriz arr , iterar a través y eliminar cada elemento comenzando desde el primer elemento (el índice 0) hasta que la función func devuelva true cuando el elemento iterado se pasa a través de él. +Luego, devuelva el resto de la matriz una vez que se cumpla la condición; de lo contrario, arr debe devolverse como una matriz vacía. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' dropElements([1, 2, 3, 4], function(n) {return n >= 3;}) debe devolver [3, 4] .' + testString: 'assert.deepEqual(dropElements([1, 2, 3, 4], function(n) {return n >= 3;}), [3, 4], "dropElements([1, 2, 3, 4], function(n) {return n >= 3;}) should return [3, 4].");' + - text: ' dropElements([0, 1, 0, 1], function(n) {return n === 1;}) debe devolver [1, 0, 1] .' + testString: 'assert.deepEqual(dropElements([0, 1, 0, 1], function(n) {return n === 1;}), [1, 0, 1], "dropElements([0, 1, 0, 1], function(n) {return n === 1;}) should return [1, 0, 1].");' + - text: ' dropElements([1, 2, 3], function(n) {return n > 0;}) debe devolver [1, 2, 3] .' + testString: 'assert.deepEqual(dropElements([1, 2, 3], function(n) {return n > 0;}), [1, 2, 3], "dropElements([1, 2, 3], function(n) {return n > 0;}) should return [1, 2, 3].");' + - text: ' dropElements([1, 2, 3, 4], function(n) {return n > 5;}) debe devolver [] .' + testString: 'assert.deepEqual(dropElements([1, 2, 3, 4], function(n) {return n > 5;}), [], "dropElements([1, 2, 3, 4], function(n) {return n > 5;}) should return [].");' + - text: ' dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;}) debe devolver [7, 4] .' + testString: 'assert.deepEqual(dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;}), [7, 4], "dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;}) should return [7, 4].");' + - text: ' dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}) debe devolver [3, 9, 2] .' + testString: 'assert.deepEqual(dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}), [3, 9, 2], "dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}) should return [3, 9, 2].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function dropElements(arr, func) { + // Drop them elements. + return arr; +} + +dropElements([1, 2, 3], function(n) {return n < 3; }); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function dropElements(arr, func) { + // Drop them elements. + while (arr.length && !func(arr[0])) { + arr.shift(); + } + return arr; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.spanish.md new file mode 100644 index 0000000000..1f6a739cc9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true.spanish.md @@ -0,0 +1,82 @@ +--- +id: a10d2431ad0c6a099a4b8b52 +title: Everything Be True +localeTitle: Todo sea verdad +isRequired: true +challengeType: 5 +--- + +## Description +
    +Compruebe si el predicado (segundo argumento) es verdadero en todos los elementos de una colección (primer argumento). +En otras palabras, se le da una colección de objetos de matriz. El predicado pre será una propiedad de objeto y debe devolver true si su valor es truthy . De lo contrario, devuelve false . +En JavaScript, los valores de truthy son valores que se convierten en true cuando se evalúan en un contexto booleano. +Recuerde, puede acceder a las propiedades del objeto a través de la notación de puntos o la notación de [] . +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") debe devolver el valor". + testString: 'assert.strictEqual(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"), true, "truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") should return true.");' + - text: ' truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") debe devolver falso. + testString: 'assert.strictEqual(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"), false, "truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex") should return false.");' + - text: ' truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age") debe devolver falso. + testString: 'assert.strictEqual(truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 2}, {"user": "Dipsy", "sex": "male", "age": 0}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age"), false, "truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age") should return false.");' + - text: ' truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat") debe devolver falso ' + testString: 'assert.strictEqual(truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat"), false, "truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat") should return false");' + - text: ' truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat") debe devolver true ' + testString: 'assert.strictEqual(truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat"), true, "truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat") should return true");' + - text: ' truthCheck([{"single": "yes"}], "single") debe devolver verdadero' + testString: 'assert.strictEqual(truthCheck([{"single": "yes"}], "single"), true, "truthCheck([{"single": "yes"}], "single") should return true");' + - text: ' truthCheck([{"single": ""}, {"single": "double"}], "single") debe devolver falso' + testString: 'assert.strictEqual(truthCheck([{"single": ""}, {"single": "double"}], "single"), false, "truthCheck([{"single": ""}, {"single": "double"}], "single") should return false");' + - text: ' truthCheck([{"single": "double"}, {"single": undefined}], "single") debe devolver falso' + testString: 'assert.strictEqual(truthCheck([{"single": "double"}, {"single": undefined}], "single"), false, "truthCheck([{"single": "double"}, {"single": undefined}], "single") should return false");' + - text: ' truthCheck([{"single": "double"}, {"single": NaN}], "single") debe devolver falso' + testString: 'assert.strictEqual(truthCheck([{"single": "double"}, {"single": NaN}], "single"), false, "truthCheck([{"single": "double"}, {"single": NaN}], "single") should return false");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function truthCheck(collection, pre) { + // Is everyone being true? + return pre; +} + +truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function truthCheck(collection, pre) { + // Does everyone have one of these? + return collection.every(function(e) { return e[pre]; }); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.spanish.md new file mode 100644 index 0000000000..211c8c8d5e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person.spanish.md @@ -0,0 +1,132 @@ +--- +id: a2f1d72d9b908d0bd72bb9f6 +title: Make a Person +localeTitle: Hacer una persona +challengeType: 5 +--- + +## Description +
    +Rellene el constructor de objetos con los siguientes métodos a continuación: +
    getFirstName() +getLastName() +getFullName() +setFirstName(first) +setLastName(last) +setFullName(firstAndLast)
    +Ejecute las pruebas para ver el resultado esperado para cada método. +Los métodos que toman un argumento deben aceptar solo un argumento y tiene que ser una cadena. +Estos métodos deben ser los únicos medios disponibles para interactuar con el objeto. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Object.keys(bob).length debe devolver 6. + testString: 'assert.deepEqual(Object.keys(bob).length, 6, "Object.keys(bob).length should return 6.");' + - text: bob instanceof Person debe devolver verdadero. + testString: 'assert.deepEqual(bob instanceof Person, true, "bob instanceof Person should return true.");' + - text: bob.firstName debe devolver undefined. + testString: 'assert.deepEqual(bob.firstName, undefined, "bob.firstName should return undefined.");' + - text: bob.lastName debe devolver undefined. + testString: 'assert.deepEqual(bob.lastName, undefined, "bob.lastName should return undefined.");' + - text: bob.getFirstName() debería devolver "Bob". + testString: 'assert.deepEqual(bob.getFirstName(), "Bob", "bob.getFirstName() should return "Bob".");' + - text: bob.getLastName() debería devolver "Ross". + testString: 'assert.deepEqual(bob.getLastName(), "Ross", "bob.getLastName() should return "Ross".");' + - text: bob.getFullName() debería devolver "Bob Ross". + testString: 'assert.deepEqual(bob.getFullName(), "Bob Ross", "bob.getFullName() should return "Bob Ross".");' + - text: bob.getFullName() debería devolver "Haskell Ross" después de bob.setFirstName("Haskell") . + testString: 'assert.strictEqual((function () { bob.setFirstName("Haskell"); return bob.getFullName(); })(), "Haskell Ross", "bob.getFullName() should return "Haskell Ross" after bob.setFirstName("Haskell").");' + - text: bob.getFullName() debe devolver "Haskell Curry" después de bob.setLastName("Curry") . + testString: 'assert.strictEqual((function () { var _bob=new Person("Haskell Ross"); _bob.setLastName("Curry"); return _bob.getFullName(); })(), "Haskell Curry", "bob.getFullName() should return "Haskell Curry" after bob.setLastName("Curry").");' + - text: bob.getFullName() debe devolver "Haskell Curry" después de bob.setFullName("Haskell Curry") . + testString: 'assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getFullName(); })(), "Haskell Curry", "bob.getFullName() should return "Haskell Curry" after bob.setFullName("Haskell Curry").");' + - text: bob.getFirstName() debe devolver "Haskell" después de bob.setFullName("Haskell Curry") . + testString: 'assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getFirstName(); })(), "Haskell", "bob.getFirstName() should return "Haskell" after bob.setFullName("Haskell Curry").");' + - text: bob.getLastName() debe devolver "Curry" después de bob.setFullName("Haskell Curry") . + testString: 'assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getLastName(); })(), "Curry", "bob.getLastName() should return "Curry" after bob.setFullName("Haskell Curry").");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +var Person = function(firstAndLast) { + // Complete the method below and implement the others similarly + this.getFullName = function() { + return ""; + }; + return firstAndLast; +}; + +var bob = new Person('Bob Ross'); +bob.getFullName(); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var Person = function(firstAndLast) { + + var firstName, lastName; + + function updateName(str) { + firstName = str.split(" ")[0]; + lastName = str.split(" ")[1]; + } + + updateName(firstAndLast); + + this.getFirstName = function(){ + return firstName; + }; + + this.getLastName = function(){ + return lastName; + }; + + this.getFullName = function(){ + return firstName + " " + lastName; + }; + + this.setFirstName = function(str){ + firstName = str; + }; + + + this.setLastName = function(str){ + lastName = str; + }; + + this.setFullName = function(str){ + updateName(str); + }; +}; + +var bob = new Person('Bob Ross'); +bob.getFullName(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.spanish.md new file mode 100644 index 0000000000..e578393b83 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris.spanish.md @@ -0,0 +1,79 @@ +--- +id: af4afb223120f7348cdfc9fd +title: Map the Debris +localeTitle: Mapa de los escombros +challengeType: 5 +--- + +## Description +
    +Devuelve una nueva matriz que transforma la altitud promedio de los elementos en sus períodos orbitales (en segundos). +La matriz contendrá objetos en el formato {name: 'name', avgAlt: avgAlt} . +Puedes leer sobre periodos orbitales en Wikipedia . +Los valores deben redondearse al número entero más cercano. El cuerpo que está siendo orbitado es la Tierra. +El radio de la Tierra es 6367.4447 kilómetros, y el valor GM de la Tierra es 398600.4418 km 3 s -2 . +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]) debe devolver [{name: "sputnik", orbitalPeriod: 86400}] .' + testString: 'assert.deepEqual(orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]), [{name: "sputnik", orbitalPeriod: 86400}], "orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]) should return [{name: "sputnik", orbitalPeriod: 86400}].");' + - text: ' orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]) debe devolver [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}] . ' + testString: 'assert.deepEqual(orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]), [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}], "orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]) should return [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function orbitalPeriod(arr) { + var GM = 398600.4418; + var earthRadius = 6367.4447; + return arr; +} + +orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function orbitalPeriod(arr) { + var GM = 398600.4418; + var earthRadius = 6367.4447; + var TAU = 2 * Math.PI; + return arr.map(function(obj) { + return { + name: obj.name, + orbitalPeriod: Math.round(TAU * Math.sqrt(Math.pow(obj.avgAlt+earthRadius, 3)/GM)) + }; + }); +} + +orbitalPeriod([{name : "sputkin", avgAlt : 35873.5553}]); + +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.spanish.md new file mode 100644 index 0000000000..102a6ff040 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters.spanish.md @@ -0,0 +1,77 @@ +--- +id: af7588ade1100bde429baf20 +title: Missing letters +localeTitle: Cartas perdidas +isRequired: true +challengeType: 5 +--- + +## Description +
    +Encuentre la letra que falta en el rango de la letra pasada y devuélvala. +Si todas las letras están presentes en el rango, devuelve indefinido. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: fearNotLetter("abce") debe devolver "d". + testString: 'assert.deepEqual(fearNotLetter("abce"), "d", "fearNotLetter("abce") should return "d".");' + - text: fearNotLetter("abcdefghjklmno") debe devolver "i". + testString: 'assert.deepEqual(fearNotLetter("abcdefghjklmno"), "i", "fearNotLetter("abcdefghjklmno") should return "i".");' + - text: fearNotLetter("stvwx") debería devolver "u". + testString: 'assert.deepEqual(fearNotLetter("stvwx"), "u", "fearNotLetter("stvwx") should return "u".");' + - text: fearNotLetter("bcdf") debe devolver "e". + testString: 'assert.deepEqual(fearNotLetter("bcdf"), "e", "fearNotLetter("bcdf") should return "e".");' + - text: fearNotLetter("abcdefghijklmnopqrstuvwxyz") debe devolver undefined. + testString: 'assert.isUndefined(fearNotLetter("abcdefghijklmnopqrstuvwxyz"), "fearNotLetter("abcdefghijklmnopqrstuvwxyz") should return undefined.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function fearNotLetter(str) { + return str; +} + +fearNotLetter("abce"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function fearNotLetter (str) { + for (var i = str.charCodeAt(0); i <= str.charCodeAt(str.length - 1); i++) { + var letter = String.fromCharCode(i); + if (str.indexOf(letter) === -1) { + return letter; + } + } + + return undefined; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.spanish.md new file mode 100644 index 0000000000..8a29aafb0f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.spanish.md @@ -0,0 +1,86 @@ +--- +id: aa7697ea2477d1316795783b +title: Pig Latin +localeTitle: Jerga +isRequired: true +challengeType: 5 +--- + +## Description +
    +Traducir la cadena proporcionada a cerdo latino. +Pig Latin toma la primera consonante (o agrupamiento de consonantes) de una palabra en inglés, la mueve al final de la palabra y los sufijos "ay". +Si una palabra comienza con una vocal, simplemente agrega "camino" al final. +Se garantiza que las cadenas de entrada son palabras en inglés en minúsculas. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: translatePigLatin("california") debe devolver "aliforniacay". + testString: 'assert.deepEqual(translatePigLatin("california"), "aliforniacay", "translatePigLatin("california") should return "aliforniacay".");' + - text: translatePigLatin("paragraphs") debe devolver "aragraphspay". + testString: 'assert.deepEqual(translatePigLatin("paragraphs"), "aragraphspay", "translatePigLatin("paragraphs") should return "aragraphspay".");' + - text: translatePigLatin("glove") debe devolver "overglay". + testString: 'assert.deepEqual(translatePigLatin("glove"), "oveglay", "translatePigLatin("glove") should return "oveglay".");' + - text: translatePigLatin("algorithm") debe devolver "algorithmway". + testString: 'assert.deepEqual(translatePigLatin("algorithm"), "algorithmway", "translatePigLatin("algorithm") should return "algorithmway".");' + - text: translatePigLatin("eight") debe devolver "eightway". + testString: 'assert.deepEqual(translatePigLatin("eight"), "eightway", "translatePigLatin("eight") should return "eightway".");' + - text: Debe manejar las palabras donde la primera vocal viene al final de la palabra. + testString: 'assert.deepEqual(translatePigLatin("schwartz"), "artzschway", "Should handle words where the first vowel comes in the end of the word.");' + - text: Debe manejar palabras sin vocales. + testString: 'assert.deepEqual(translatePigLatin("rhythm"), "rhythmay", "Should handle words without vowels.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function translatePigLatin(str) { + return str; +} + +translatePigLatin("consonant"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function translatePigLatin(str) { + if (isVowel(str.charAt(0))) return str + "way"; + var front = []; + str = str.split(''); + while (str.length && !isVowel(str[0])) { + front.push(str.shift()); + } + return [].concat(str, front).join('') + 'ay'; +} + +function isVowel(c) { + return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.spanish.md new file mode 100644 index 0000000000..9e2ac1e04d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace.spanish.md @@ -0,0 +1,78 @@ +--- +id: a0b5010f579e69b815e7c5d6 +title: Search and Replace +localeTitle: Buscar y reemplazar +isRequired: true +challengeType: 5 +--- + +## Description +
    +Realice una búsqueda y reemplace la oración usando los argumentos proporcionados y devuelva la nueva oración. +primer argumento es la oración para realizar la búsqueda y reemplazar. +Segundo argumento es la palabra que reemplazará (antes). +Tercer argumento es con lo que reemplazará el segundo argumento por (después). +Nota
    Conserve el caso del primer carácter en la palabra original cuando lo reemplace. Por ejemplo, si quiere reemplazar la palabra "Libro" con la palabra "perro", debe ser reemplazada como "Perro" +Recuerde usar Lectura-Búsqueda-Preguntar si se atasca. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' myReplace("Let us go to the store", "store", "mall") debe devolver "Vamos myReplace("Let us go to the store", "store", "mall") ".' + testString: 'assert.deepEqual(myReplace("Let us go to the store", "store", "mall"), "Let us go to the mall", "myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".");' + - text: ' myReplace("He is Sleeping on the couch", "Sleeping", "sitting") debe devolver "Está sentado en el sofá". + testString: 'assert.deepEqual(myReplace("He is Sleeping on the couch", "Sleeping", "sitting"), "He is Sitting on the couch", "myReplace("He is Sleeping on the couch", "Sleeping", "sitting") should return "He is Sitting on the couch".");' + - text: ' myReplace("This has a spellngi error", "spellngi", "spelling") debe devolver "Esto tiene un error de ortografía".' + testString: 'assert.deepEqual(myReplace("This has a spellngi error", "spellngi", "spelling"), "This has a spelling error", "myReplace("This has a spellngi error", "spellngi", "spelling") should return "This has a spelling error".");' + - text: ' myReplace("His name is Tom", "Tom", "john") debe devolver "Su nombre es John". + testString: 'assert.deepEqual(myReplace("His name is Tom", "Tom", "john"), "His name is John", "myReplace("His name is Tom", "Tom", "john") should return "His name is John".");' + - text: ' myReplace("Let us get back to more Coding", "Coding", "algorithms") debería devolver "Regresemos a más Algoritmos". + testString: 'assert.deepEqual(myReplace("Let us get back to more Coding", "Coding", "algorithms"), "Let us get back to more Algorithms", "myReplace("Let us get back to more Coding", "Coding", "algorithms") should return "Let us get back to more Algorithms".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function myReplace(str, before, after) { + return str; +} + +myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function myReplace(str, before, after) { + if (before.charAt(0) === before.charAt(0).toUpperCase()) { + after = after.charAt(0).toUpperCase() + after.substring(1); + } else { + after = after.charAt(0).toLowerCase() + after.substring(1); + } + return str.replace(before, after); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.spanish.md new file mode 100644 index 0000000000..9e3553f221 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy.spanish.md @@ -0,0 +1,81 @@ +--- +id: a39963a4c10bc8b4d4f06d7e +title: Seek and Destroy +localeTitle: Buscar y destruir +isRequired: true +challengeType: 5 +--- + +## Description +
    +Se le proporcionará una matriz inicial (el primer argumento en la función del destructor), seguido de uno o más argumentos. Elimine todos los elementos de la matriz inicial que tengan el mismo valor que estos argumentos. +Nota
    Tienes que usar el objeto arguments . +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' destroyer([1, 2, 3, 1, 2, 3], 2, 3) debe devolver [1, 1] .' + testString: 'assert.deepEqual(destroyer([1, 2, 3, 1, 2, 3], 2, 3), [1, 1], "destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].");' + - text: ' destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) debe devolver [1, 5, 1] .' + testString: 'assert.deepEqual(destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3), [1, 5, 1], "destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].");' + - text: ' destroyer([3, 5, 1, 2, 2], 2, 3, 5) debe devolver [1] .' + testString: 'assert.deepEqual(destroyer([3, 5, 1, 2, 2], 2, 3, 5), [1], "destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].");' + - text: ' destroyer([2, 3, 2, 3], 2, 3) debe devolver [] .' + testString: 'assert.deepEqual(destroyer([2, 3, 2, 3], 2, 3), [], "destroyer([2, 3, 2, 3], 2, 3) should return [].");' + - text: ' destroyer(["tree", "hamburger", 53], "tree", 53) debe devolver ["hamburger"] .' + testString: 'assert.deepEqual(destroyer(["tree", "hamburger", 53], "tree", 53), ["hamburger"], "destroyer(["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].");' + - text: ' destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan") debe devolver [12,92,65] . ' + testString: 'assert.deepEqual(destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan"), [12,92,65], "destroyer(["possum", "trollo", 12, "safari", "hotdog", 92, 65, "grandma", "bugati", "trojan", "yacht"], "yacht", "possum", "trollo", "safari", "hotdog", "grandma", "bugati", "trojan") should return [12,92,65].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function destroyer(arr) { + // Remove all the values + return arr; +} + +destroyer([1, 2, 3, 1, 2, 3], 2, 3); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function destroyer(arr) { + var hash = Object.create(null); + [].slice.call(arguments, 1).forEach(function(e) { + hash[e] = true; + }); + // Remove all the values + return arr.filter(function(e) { return !(e in hash);}); +} + +destroyer([1, 2, 3, 1, 2, 3], 2, 3); + +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.spanish.md new file mode 100644 index 0000000000..1ab72a14ad --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple.spanish.md @@ -0,0 +1,90 @@ +--- +id: ae9defd7acaf69703ab432ea +title: Smallest Common Multiple +localeTitle: El múltiplo común más pequeño +isRequired: true +challengeType: 5 +--- + +## Description +
    +Encuentre el múltiplo común más pequeño de los parámetros provistos que pueden dividirse de manera uniforme por ambos, así como por todos los números secuenciales en el rango entre estos parámetros. +El rango será una matriz de dos números que no necesariamente estarán en orden numérico. +Por ejemplo, si se proporciona 1 y 3, encuentre el mínimo común múltiplo de 1 y 3 que también es divisible por todos los números entre 1 y 3. La respuesta aquí sería 6. +Recuerde usar Lectura-Búsqueda-Preguntar si te quedas atascado Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' smallestCommons([1, 5]) debe devolver un número.' + testString: 'assert.deepEqual(typeof smallestCommons([1, 5]), "number", "smallestCommons([1, 5]) should return a number.");' + - text: ' smallestCommons([1, 5]) debe devolver 60.' + testString: 'assert.deepEqual(smallestCommons([1, 5]), 60, "smallestCommons([1, 5]) should return 60.");' + - text: ' smallestCommons([5, 1]) debe devolver 60.' + testString: 'assert.deepEqual(smallestCommons([5, 1]), 60, "smallestCommons([5, 1]) should return 60.");' + - text: ' smallestCommons([2, 10]) debe devolver 2520.' + testString: 'assert.deepEqual(smallestCommons([2, 10]), 2520, "smallestCommons([2, 10]) should return 2520.");' + - text: ' smallestCommons([1, 13]) debe devolver 360360.' + testString: 'assert.deepEqual(smallestCommons([1, 13]), 360360, "smallestCommons([1, 13]) should return 360360.");' + - text: ' smallestCommons([23, 18]) debe devolver 6056820.' + testString: 'assert.deepEqual(smallestCommons([23, 18]), 6056820, "smallestCommons([23, 18]) should return 6056820.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function smallestCommons(arr) { + return arr; +} + + +smallestCommons([1,5]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function gcd(a, b) { + while (b !== 0) { + a = [b, b = a % b][0]; + } + return a; +} + +function lcm(a, b) { + return (a * b) / gcd(a, b); +} + +function smallestCommons(arr) { + arr.sort(function(a,b) {return a-b;}); + var rng = []; + for (var i = arr[0]; i <= arr[1]; i++) { + rng.push(i); + } + return rng.reduce(lcm); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.spanish.md new file mode 100644 index 0000000000..d9026c9bfc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union.spanish.md @@ -0,0 +1,72 @@ +--- +id: a105e963526e7de52b219be9 +title: Sorted Union +localeTitle: Unión ordenada +isRequired: true +challengeType: 5 +--- + +## Description +
    +Escriba una función que tome dos o más matrices y devuelva una nueva matriz de valores únicos en el orden de las matrices proporcionadas originales. +En otras palabras, todos los valores presentes de todas las matrices deben incluirse en su orden original, pero sin duplicados en la matriz final. +Los números únicos deben ordenarse según su orden original, pero la matriz final no debe ordenarse en orden numérico. +Verifique las pruebas de aserción para ver ejemplos. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]) debe devolver [1, 3, 2, 5, 4] .' + testString: 'assert.deepEqual(uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), [1, 3, 2, 5, 4], "uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]) should return [1, 3, 2, 5, 4].");' + - text: ' uniteUnique([1, 3, 2], [1, [5]], [2, [4]]) debe devolver [1, 3, 2, [5], [4]] .' + testString: 'assert.deepEqual(uniteUnique([1, 3, 2], [1, [5]], [2, [4]]), [1, 3, 2, [5], [4]], "uniteUnique([1, 3, 2], [1, [5]], [2, [4]]) should return [1, 3, 2, [5], [4]].");' + - text: ' uniteUnique([1, 2, 3], [5, 2, 1]) debe devolver [1, 2, 3, 5] .' + testString: 'assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1]), [1, 2, 3, 5], "uniteUnique([1, 2, 3], [5, 2, 1]) should return [1, 2, 3, 5].");' + - text: ' uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]) debe devolver [1, 2, 3, 5, 4, 6, 7, 8] . + testString: 'assert.deepEqual(uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), [1, 2, 3, 5, 4, 6, 7, 8], "uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]) should return [1, 2, 3, 5, 4, 6, 7, 8].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function uniteUnique(arr) { + return arr; +} + +uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function uniteUnique(arr) { + return [].slice.call(arguments).reduce(function(a, b) { + return [].concat(a, b.filter(function(e) {return a.indexOf(e) === -1;})); + }, []); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.spanish.md new file mode 100644 index 0000000000..146f6018fc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case.spanish.md @@ -0,0 +1,74 @@ +--- +id: a103376db3ba46b2d50db289 +title: Spinal Tap Case +localeTitle: Caja del grifo espinal +isRequired: true +challengeType: 5 +--- + +## Description +
    +Convertir una cadena a la caja espinal. El caso de la columna vertebral está compuesto por guiones en minúsculas. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: spinalCase("This Is Spinal Tap") debe devolver "this-is-spinal-tap" . + testString: 'assert.deepEqual(spinalCase("This Is Spinal Tap"), "this-is-spinal-tap", "spinalCase("This Is Spinal Tap") should return "this-is-spinal-tap".");' + - text: spinalCase("thisIsSpinal Tap") debe devolver "this-is-spinal-tap" . + testString: 'assert.strictEqual(spinalCase("thisIsSpinalTap"), "this-is-spinal-tap", "spinalCase("thisIsSpinalTap") should return "this-is-spinal-tap".");' + - text: spinalCase("The_Andy_ Griffith_Show") debe devolver "the-andy-griffith-show" . + testString: 'assert.strictEqual(spinalCase("The_Andy_Griffith_Show"), "the-andy-griffith-show", "spinalCase("The_Andy_Griffith_Show") should return "the-andy-griffith-show".");' + - text: spinalCase("Teletubbies say Eh-oh") debe devolver "teletubbies-say-eh-oh" . + testString: 'assert.strictEqual(spinalCase("Teletubbies say Eh-oh"), "teletubbies-say-eh-oh", "spinalCase("Teletubbies say Eh-oh") should return "teletubbies-say-eh-oh".");' + - text: spinalCase("AllThe-small Things") debería devolver "all-the-small-things" . + testString: 'assert.strictEqual(spinalCase("AllThe-small Things"), "all-the-small-things", "spinalCase("AllThe-small Things") should return "all-the-small-things".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function spinalCase(str) { + // "It's such a fine line between stupid, and clever." + // --David St. Hubbins + return str; +} + +spinalCase('This Is Spinal Tap'); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function spinalCase(str) { + // "It's such a fine line between stupid, and clever." + // --David St. Hubbins + str = str.replace(/([a-z](?=[A-Z]))/g, '$1 '); + return str.toLowerCase().replace(/\ |\_/g, '-'); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.spanish.md new file mode 100644 index 0000000000..fae59d64bc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller.spanish.md @@ -0,0 +1,77 @@ +--- +id: ab306dbdcc907c7ddfc30830 +title: Steamroller +localeTitle: Apisonadora +isRequired: true +challengeType: 5 +--- + +## Description +
    +Aplanar una matriz anidada. Debe tener en cuenta los diferentes niveles de anidación. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' steamrollArray([[["a"]], [["b"]]]) debe devolver ["a", "b"] .' + testString: 'assert.deepEqual(steamrollArray([[["a"]], [["b"]]]), ["a", "b"], "steamrollArray([[["a"]], [["b"]]]) should return ["a", "b"].");' + - text: ' steamrollArray([1, [2], [3, [[4]]]]) debe devolver [1, 2, 3, 4] .' + testString: 'assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4], "steamrollArray([1, [2], [3, [[4]]]]) should return [1, 2, 3, 4].");' + - text: ' steamrollArray([1, [], [3, [[4]]]]) debe devolver [1, 3, 4] .' + testString: 'assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4], "steamrollArray([1, [], [3, [[4]]]]) should return [1, 3, 4].");' + - text: ' steamrollArray([1, {}, [3, [[4]]]]) debe devolver [1, {}, 3, 4] .' + testString: 'assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4], "steamrollArray([1, {}, [3, [[4]]]]) should return [1, {}, 3, 4].");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function steamrollArray(arr) { + // I'm a steamroller, baby + return arr; +} + +steamrollArray([1, [2], [3, [[4]]]]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function steamrollArray(arr) { + if (!Array.isArray(arr)) { + return [arr]; + } + var out = []; + arr.forEach(function(e) { + steamrollArray(e).forEach(function(v) { + out.push(v); + }); + }); + return out; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.spanish.md new file mode 100644 index 0000000000..2de6124ff1 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range.spanish.md @@ -0,0 +1,75 @@ +--- +id: a3566b1109230028080c9345 +title: Sum All Numbers in a Range +localeTitle: Suma todos los números en un rango +isRequired: true +challengeType: 5 +--- + +## Description +
    +Te pasaremos una matriz de dos números. Devuelve la suma de esos dos números más la suma de todos los números entre ellos. +El número más bajo no siempre vendrá primero. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' sumAll([1, 4]) debe devolver un número.' + testString: 'assert(typeof sumAll([1, 4]) === "number", "sumAll([1, 4]) should return a number.");' + - text: ' sumAll([1, 4]) debe devolver 10.' + testString: 'assert.deepEqual(sumAll([1, 4]), 10, "sumAll([1, 4]) should return 10.");' + - text: ' sumAll([4, 1]) debe devolver 10.' + testString: 'assert.deepEqual(sumAll([4, 1]), 10, "sumAll([4, 1]) should return 10.");' + - text: ' sumAll([5, 10]) debe devolver 45.' + testString: 'assert.deepEqual(sumAll([5, 10]), 45, "sumAll([5, 10]) should return 45.");' + - text: ' sumAll([10, 5]) debe devolver 45.' + testString: 'assert.deepEqual(sumAll([10, 5]), 45, "sumAll([10, 5]) should return 45.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function sumAll(arr) { + return 1; +} + +sumAll([1, 4]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function sumAll(arr) { + var sum = 0; + arr.sort(function(a,b) {return a-b;}); + for (var i = arr[0]; i <= arr[1]; i++) { + sum += i; + } + return sum; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.spanish.md new file mode 100644 index 0000000000..3531b3eaef --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers.spanish.md @@ -0,0 +1,82 @@ +--- +id: a5229172f011153519423690 +title: Sum All Odd Fibonacci Numbers +localeTitle: Suma todos los números impares de Fibonacci +isRequired: true +challengeType: 5 +--- + +## Description +
    +Dado un número entero positivo num , devolver la suma de todos los números impares de Fibonacci que son menos que o igual a num . +Los dos primeros números en la secuencia de Fibonacci son 1 y 1. Cada número adicional en la secuencia es la suma de los dos números anteriores. Los primeros seis números de la secuencia de Fibonacci son 1, 1, 2, 3, 5 y 8. +Por ejemplo, sumFibs(10) debe devolver 10 porque todos los números impares de Fibonacci menores o iguales a 10 son 1, 1, 3, y 5. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: sumFibs(1) debe devolver un número. + testString: 'assert(typeof sumFibs(1) === "number", "sumFibs(1) should return a number.");' + - text: sumFibs(1000) debe devolver 1785. + testString: 'assert(sumFibs(1000) === 1785, "sumFibs(1000) should return 1785.");' + - text: sumFibs(4000000) debe devolver 4613732. + testString: 'assert(sumFibs(4000000) === 4613732, "sumFibs(4000000) should return 4613732.");' + - text: sumFibs(4) debe devolver 5. + testString: 'assert(sumFibs(4) === 5, "sumFibs(4) should return 5.");' + - text: sumFibs(75024) debe devolver 60696. + testString: 'assert(sumFibs(75024) === 60696, "sumFibs(75024) should return 60696.");' + - text: sumFibs(75025) debe devolver 135721. + testString: 'assert(sumFibs(75025) === 135721, "sumFibs(75025) should return 135721.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function sumFibs(num) { + return num; +} + +sumFibs(4); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function sumFibs(num) { + var a = 1; + var b = 1; + var s = 0; + while (a <= num) { + if (a % 2 !== 0) { + s += a; + } + a = [b, b=b+a][0]; + } + return s; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.spanish.md new file mode 100644 index 0000000000..a3a03a3522 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes.spanish.md @@ -0,0 +1,89 @@ +--- +id: a3bfc1673c0526e06d3ac698 +title: Sum All Primes +localeTitle: Suma todos los premios +isRequired: true +challengeType: 5 +--- + +## Description +
    +Suma todos los números primos hasta e incluyendo el número proporcionado. +Un número primo se define como un número mayor que uno y tiene solo dos divisores, uno y sí mismo. Por ejemplo, 2 es un número primo porque solo es divisible entre uno y dos. +El número proporcionado puede no ser un número primo. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: sumPrimes(10) debe devolver un número. + testString: 'assert.deepEqual(typeof sumPrimes(10), "number", "sumPrimes(10) should return a number.");' + - text: sumPrimes(10) debe devolver 17. + testString: 'assert.deepEqual(sumPrimes(10), 17, "sumPrimes(10) should return 17.");' + - text: sumPrimes(977) debe devolver 73156. + testString: 'assert.deepEqual(sumPrimes(977), 73156, "sumPrimes(977) should return 73156.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function sumPrimes(num) { + return num; +} + +sumPrimes(10); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function eratosthenesArray(n) { + var primes = []; + if (n > 2) { + var half = n>>1; + var sieve = Array(half); + for (var i = 1, limit = Math.sqrt(n)>>1; i <= limit; i++) { + if (!sieve[i]) { + for (var step = 2*i+1, j = (step*step)>>1; j < half; j+=step) { + sieve[j] = true; + } + } + } + primes.push(2); + for (var p = 1; p < half; p++) { + if (!sieve[p]) primes.push(2*p+1); + } + } + return primes; +} + +function sumPrimes(num) { + return eratosthenesArray(num+1).reduce(function(a,b) {return a+b;}, 0); +} + +sumPrimes(10); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.spanish.md new file mode 100644 index 0000000000..54e7b2ac50 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou.spanish.md @@ -0,0 +1,85 @@ +--- +id: a8e512fbe388ac2f9198f0fa +title: Wherefore art thou +localeTitle: Donde estás +isRequired: true +challengeType: 5 +--- + +## Description +
    +Haga una función que examine una matriz de objetos (primer argumento) y devuelva una matriz de todos los objetos que tengan pares de nombre y valor coincidentes (segundo argumento). Cada par de nombre y valor del objeto de origen debe estar presente en el objeto de la colección si se va a incluir en la matriz devuelta. +Por ejemplo, si el primer argumento es [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }] , y el segundo argumento es { last: "Capulet" } , luego debe devolver el tercer objeto de la matriz (el primer argumento), ya que contiene el nombre y su valor, que se pasó como el segundo argumento. +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) debe devolver [{ first: "Tybalt", last: "Capulet" }] . ' + testString: 'assert.deepEqual(whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }), [{ first: "Tybalt", last: "Capulet" }], "whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }) should return [{ first: "Tybalt", last: "Capulet" }].");' + - text: ' whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) debe devolver [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }] . ' + testString: 'assert.deepEqual(whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }), [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], "whatIsInAName([{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }], { "apple": 1 }) should return [{ "apple": 1 }, { "apple": 1 }, { "apple": 1, "bat": 2 }].");' + - text: ' whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) debe devolver [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }] . ' + testString: 'assert.deepEqual(whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }), [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], "whatIsInAName([{ "apple": 1, "bat": 2 }, { "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie": 2 }].");' + - text: ' whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) debe devolver [{ "apple": 1, "bat": 2, "cookie": 2 }] . ' + testString: 'assert.deepEqual(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }), [{ "apple": 1, "bat": 2, "cookie": 2 }], "whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }], { "apple": 1, "cookie": 2 }) should return [{ "apple": 1, "bat": 2, "cookie": 2 }].");' + - text: ' whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) debe devolver [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }] . ' + testString: 'assert.deepEqual(whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, {"bat":2}], { "apple": 1, "bat": 2 }), [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }], "whatIsInAName([{ "apple": 1, "bat": 2 }, { "apple": 1 }, { "apple": 1, "bat": 2, "cookie": 2 }, { "bat":2 }], { "apple": 1, "bat": 2 }) should return [{ "apple": 1, "bat": 2 }, { "apple": 1, "bat": 2, "cookie":2 }].");' + - text: ' whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) debe devolver [] ' + testString: 'assert.deepEqual(whatIsInAName([{ "a": 1, "b": 2, "c": 3 }], { "a": 1, "b": 9999, "c": 3 }), [], "whatIsInAName([{"a": 1, "b": 2, "c": 3}], {"a": 1, "b": 9999, "c": 3}) should return []");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function whatIsInAName(collection, source) { + // What's in a name? + var arr = []; + // Only change code below this line + + + // Only change code above this line + return arr; +} + +whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function whatIsInAName(collection, source) { + var arr = []; + var keys = Object.keys(source); + collection.forEach(function(e) { + if(keys.every(function(key) {return e[key] === source[key];})) { + arr.push(e); + } + }); + return arr; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.spanish.md new file mode 100644 index 0000000000..aba9467d1e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher.spanish.md @@ -0,0 +1,94 @@ +--- +id: 56533eb9ac21ba0edf2244e2 +title: Caesars Cipher +localeTitle: Cifrado de Caesars +challengeType: 5 +isRequired: true +--- + +## Description +
    +Uno de los cifrados más simples y más conocidos es el Caesar cipher , también conocido como shift cipher . En un shift cipher los significados de las letras se desplazan en una cantidad determinada. +Un uso moderno común es el cifrado ROT13 , donde los valores de las letras se desplazan en 13 lugares. Así, 'A' ↔ 'N', 'B' ↔ 'O' y así sucesivamente. +Escribir una función que toma una cadena codificada ROT13 como entrada y devuelve una cadena decodificada. +Todas las letras serán mayúsculas. No transforme ningún carácter no alfabético (es decir, espacios, puntuación), pero sí páselos. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: rot13("SERR PBQR PNZC") debe decodificar a FREE CODE CAMP + testString: 'assert(rot13("SERR PBQR PNZC") === "FREE CODE CAMP", "rot13("SERR PBQR PNZC") should decode to FREE CODE CAMP");' + - text: rot13("SERR CVMMN!") debe decodificar a FREE PIZZA! + testString: 'assert(rot13("SERR CVMMN!") === "FREE PIZZA!", "rot13("SERR CVMMN!") should decode to FREE PIZZA!");' + - text: rot13("SERR YBIR?") debe decodificar a FREE LOVE? + testString: 'assert(rot13("SERR YBIR?") === "FREE LOVE?", "rot13("SERR YBIR?") should decode to FREE LOVE?");' + - text: rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") debe decodificarse a THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. + testString: 'assert(rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") === "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.", "rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.") should decode to THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function rot13(str) { // LBH QVQ VG! + + return str; +} + +// Change the inputs below to test +rot13("SERR PBQR PNZC"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var lookup = { + 'A': 'N','B': 'O','C': 'P','D': 'Q', + 'E': 'R','F': 'S','G': 'T','H': 'U', + 'I': 'V','J': 'W','K': 'X','L': 'Y', + 'M': 'Z','N': 'A','O': 'B','P': 'C', + 'Q': 'D','R': 'E','S': 'F','T': 'G', + 'U': 'H','V': 'I','W': 'J','X': 'K', + 'Y': 'L','Z': 'M' +}; + +function rot13(encodedStr) { + var codeArr = encodedStr.split(""); // String to Array + var decodedArr = []; // Your Result goes here + // Only change code below this line + + decodedArr = codeArr.map(function(letter) { + if(lookup.hasOwnProperty(letter)) { + letter = lookup[letter]; + } + return letter; + }); + + // Only change code above this line + return decodedArr.join(""); // Array to String +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.spanish.md new file mode 100644 index 0000000000..3b8df5beaf --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register.spanish.md @@ -0,0 +1,137 @@ +--- +id: aa2e6f85cab2ab736c9a9b24 +title: Cash Register +localeTitle: Caja registradora +isRequired: true +challengeType: 5 +--- + +## Description +
    +Diseñe una función de cajón de la caja registradora checkCashRegister() que acepte el precio de compra como primer argumento ( price ), el pago como segundo argumento ( cash ) y el cajón de efectivo ( cid ) como tercer argumento. +cid es una matriz 2D que muestra la moneda disponible. +La función checkCashRegister() siempre debe devolver un objeto con una clave de status y una clave de change . +Devuelva {status: "INSUFFICIENT_FUNDS", change: []} si el efectivo en el cajón es inferior al cambio debido, o si no puede devolver el cambio exacto. +Devuelva {status: "CLOSED", change: [...]} con cash-in-drawer como valor del change clave si es igual al cambio debido. +De lo contrario, devuelva {status: "OPEN", change: [...]} , con el cambio en monedas y billetes, ordenados de mayor a menor, como el valor de la clave de change . +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    Unidad monetaria Cantidad
    Centavo $ 0.01 (PENNY)
    Níquel $ 0.05 (níquel)
    Moneda de diez centavos $ 0.1 (DIME)
    Trimestre $ 0.25 (TRIMESTRE)
    Dólar $ 1 (DÓLAR)
    Cinco dólares $ 5 (CINCO)
    Diez dólares $ 10 (DIEZ)
    Veinte dólares $ 20 (VEINTE)
    Cien dolares $ 100 (100)
    +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: ' checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) debe devolver un objeto. ' + testString: 'assert.deepEqual(Object.prototype.toString.call(checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]])), "[object Object]", "checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) should return an object.");' + - text: ' checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) debe devolver {status: "OPEN", change: [["QUARTER", 0.5]]} . ' + testString: 'assert.deepEqual(checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]), {status: "OPEN", change: [["QUARTER", 0.5]]}, "checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) should return {status: "OPEN", change: [["QUARTER", 0.5]]}.");' + - text: ' checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) debe devolver {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]} . ' + testString: 'assert.deepEqual(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]), {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}, "checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]) should return {status: "OPEN", change: [["TWENTY", 60], ["TEN", 20], ["FIVE", 15], ["ONE", 1], ["QUARTER", 0.5], ["DIME", 0.2], ["PENNY", 0.04]]}.");' + - text: ' checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) debe devolver {status: "INSUFFICIENT_FUNDS", change: []} . ' + testString: 'assert.deepEqual(checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]), {status: "INSUFFICIENT_FUNDS", change: []}, "checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) should return {status: "INSUFFICIENT_FUNDS", change: []}.");' + - text: ' checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) debe devolver {status: "INSUFFICIENT_FUNDS", change: []} . ' + testString: 'assert.deepEqual(checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]), {status: "INSUFFICIENT_FUNDS", change: []}, "checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) should return {status: "INSUFFICIENT_FUNDS", change: []}.");' + - text: ' checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) debe devolver {status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]} . ' + testString: 'assert.deepEqual(checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]), {status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}, "checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]) should return {status: "CLOSED", change: [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]}.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function checkCashRegister(price, cash, cid) { + var change; + // Here is your change, ma'am. + return change; +} + +// Example cash-in-drawer array: +// [["PENNY", 1.01], +// ["NICKEL", 2.05], +// ["DIME", 3.1], +// ["QUARTER", 4.25], +// ["ONE", 90], +// ["FIVE", 55], +// ["TEN", 20], +// ["TWENTY", 60], +// ["ONE HUNDRED", 100]] + +checkCashRegister(19.5, 20, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var denom = [ + { name: 'ONE HUNDRED', val: 100}, + { name: 'TWENTY', val: 20}, + { name: 'TEN', val: 10}, + { name: 'FIVE', val: 5}, + { name: 'ONE', val: 1}, + { name: 'QUARTER', val: 0.25}, + { name: 'DIME', val: 0.1}, + { name: 'NICKEL', val: 0.05}, + { name: 'PENNY', val: 0.01} +]; + +function checkCashRegister(price, cash, cid) { + var output = {status: null, change: []}; + var change = cash - price; + var register = cid.reduce(function(acc, curr) { + acc.total += curr[1]; + acc[curr[0]] = curr[1]; + return acc; + }, {total: 0}); + if(register.total === change) { + output.status = 'CLOSED'; + output.change = cid; + return output; + } + if(register.total < change) { + output.status = 'INSUFFICIENT_FUNDS'; + return output; + } + var change_arr = denom.reduce(function(acc, curr) { + var value = 0; + while(register[curr.name] > 0 && change >= curr.val) { + change -= curr.val; + register[curr.name] -= curr.val; + value += curr.val; + change = Math.round(change * 100) / 100; + } + if(value > 0) { + acc.push([ curr.name, value ]); + } + return acc; + }, []); + if(change_arr.length < 1 || change > 0) { + output.status = 'INSUFFICIENT_FUNDS'; + return output; + } + output.status = 'OPEN'; + output.change = change_arr; + return output; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.spanish.md new file mode 100644 index 0000000000..a01a78d990 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker.spanish.md @@ -0,0 +1,98 @@ +--- +id: aaa48de84e1ecc7c742e1124 +title: Palindrome Checker +localeTitle: Comprobador de palíndromo +isRequired: true +challengeType: 5 +--- + +## Description +
    +Devuelve true si la cadena dada es un palíndromo. De lo contrario, devuelve false . +Un palíndromo es una palabra u oración que se escribe de la misma manera tanto hacia adelante como hacia atrás, ignorando la puntuación, el caso y el espaciado. +Nota
    Deberá eliminar todos los caracteres no alfanuméricos (puntuación, espacios y símbolos) y convertir todo en el mismo caso (mayúsculas o minúsculas) para comprobar si hay palíndromos. +Pasaremos cadenas con distintos formatos, como "racecar" , "RaceCar" y "race CAR" entre otros. +También pasaremos cadenas con símbolos especiales, como "2A3*3a2" , "2A3 3a2" y "2_A3*3#A2" . +Recuerda usar Read-Search-Ask si te atascas. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: palindrome("eye") debe devolver un valor booleano. + testString: 'assert(typeof palindrome("eye") === "boolean", "palindrome("eye") should return a boolean.");' + - text: palindrome("eye") debe devolver verdadero. + testString: 'assert(palindrome("eye") === true, "palindrome("eye") should return true.");' + - text: palindrome("_eye") debe devolver verdadero. + testString: 'assert(palindrome("_eye") === true, "palindrome("_eye") should return true.");' + - text: palindrome("race car") debe devolver verdadero. + testString: 'assert(palindrome("race car") === true, "palindrome("race car") should return true.");' + - text: palindrome("not a palindrome") debe devolver falso. + testString: 'assert(palindrome("not a palindrome") === false, "palindrome("not a palindrome") should return false.");' + - text: ' palindrome("A man, a plan, a canal. Panama") debería devolver la verdad ". + testString: 'assert(palindrome("A man, a plan, a canal. Panama") === true, "palindrome("A man, a plan, a canal. Panama") should return true.");' + - text: palindrome("never odd or even") debe devolver verdadero. + testString: 'assert(palindrome("never odd or even") === true, "palindrome("never odd or even") should return true.");' + - text: palindrome("nope") debe devolver falso. + testString: 'assert(palindrome("nope") === false, "palindrome("nope") should return false.");' + - text: palindrome("almostomla") debe devolver falso. + testString: 'assert(palindrome("almostomla") === false, "palindrome("almostomla") should return false.");' + - text: ' palindrome("My age is 0, 0 si ega ym.") debería devolver verdadero.' + testString: 'assert(palindrome("My age is 0, 0 si ega ym.") === true, "palindrome("My age is 0, 0 si ega ym.") should return true.");' + - text: palindrome("1 eye for of 1 eye.") debe devolver falso. + testString: 'assert(palindrome("1 eye for of 1 eye.") === false, "palindrome("1 eye for of 1 eye.") should return false.");' + - text: ' palindrome("0_0 (: /-\ :) 0-0") debe devolver verdadero.' + testString: 'assert(palindrome("0_0 (: /-\ :) 0-0") === true, "palindrome("0_0 (: /-\ :) 0-0") should return true.");' + - text: palindrome("five|\_/|four") debe devolver falso. + testString: 'assert(palindrome("five|\_/|four") === false, "palindrome("five|\_/|four") should return false.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function palindrome(str) { + // Good luck! + return true; +} + + + +palindrome("eye"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function palindrome(str) { + var string = str.toLowerCase().split(/[^A-Za-z0-9]/gi).join(''); + var aux = string.split(''); + if (aux.join('') === aux.reverse().join('')){ + return true; + } + + return false; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.spanish.md new file mode 100644 index 0000000000..56bb88a2ca --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter.spanish.md @@ -0,0 +1,120 @@ +--- +id: a7f4d8f2483413a6ce226cac +title: Roman Numeral Converter +localeTitle: Convertidor de números romanos +isRequired: true +challengeType: 5 +--- + +## Description +
    +Convertir el número dado en un número romano. +Todas las respuestas de los números romanos deben proporcionarse en mayúsculas. +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: convertToRoman(2) debe devolver "II". + testString: 'assert.deepEqual(convertToRoman(2), "II", "convertToRoman(2) should return "II".");' + - text: convertToRoman(3) debe devolver "III". + testString: 'assert.deepEqual(convertToRoman(3), "III", "convertToRoman(3) should return "III".");' + - text: convertToRoman(4) debe devolver "IV". + testString: 'assert.deepEqual(convertToRoman(4), "IV", "convertToRoman(4) should return "IV".");' + - text: convertToRoman(5) debe devolver "V". + testString: 'assert.deepEqual(convertToRoman(5), "V", "convertToRoman(5) should return "V".");' + - text: convertToRoman(9) debe devolver "IX". + testString: 'assert.deepEqual(convertToRoman(9), "IX", "convertToRoman(9) should return "IX".");' + - text: convertToRoman(12) debe devolver "XII". + testString: 'assert.deepEqual(convertToRoman(12), "XII", "convertToRoman(12) should return "XII".");' + - text: convertToRoman(16) debe devolver "XVI". + testString: 'assert.deepEqual(convertToRoman(16), "XVI", "convertToRoman(16) should return "XVI".");' + - text: convertToRoman(29) debe devolver "XXIX". + testString: 'assert.deepEqual(convertToRoman(29), "XXIX", "convertToRoman(29) should return "XXIX".");' + - text: convertToRoman(44) debe devolver "XLIV". + testString: 'assert.deepEqual(convertToRoman(44), "XLIV", "convertToRoman(44) should return "XLIV".");' + - text: convertToRoman(45) debe devolver "XLV" + testString: 'assert.deepEqual(convertToRoman(45), "XLV", "convertToRoman(45) should return "XLV"");' + - text: convertToRoman(68) debe devolver "LXVIII" + testString: 'assert.deepEqual(convertToRoman(68), "LXVIII", "convertToRoman(68) should return "LXVIII"");' + - text: convertToRoman(83) debe devolver "LXXXIII" + testString: 'assert.deepEqual(convertToRoman(83), "LXXXIII", "convertToRoman(83) should return "LXXXIII"");' + - text: convertToRoman(97) debe devolver "XCVII" + testString: 'assert.deepEqual(convertToRoman(97), "XCVII", "convertToRoman(97) should return "XCVII"");' + - text: convertToRoman(99) debe devolver "XCIX" + testString: 'assert.deepEqual(convertToRoman(99), "XCIX", "convertToRoman(99) should return "XCIX"");' + - text: convertToRoman(400) debería devolver "CD" + testString: 'assert.deepEqual(convertToRoman(400), "CD", "convertToRoman(400) should return "CD"");' + - text: convertToRoman(500) debe devolver "D" + testString: 'assert.deepEqual(convertToRoman(500), "D", "convertToRoman(500) should return "D"");' + - text: convertToRoman(501) debe devolver "DI" + testString: 'assert.deepEqual(convertToRoman(501), "DI", "convertToRoman(501) should return "DI"");' + - text: convertToRoman(649) debe devolver "DCXLIX" + testString: 'assert.deepEqual(convertToRoman(649), "DCXLIX", "convertToRoman(649) should return "DCXLIX"");' + - text: convertToRoman(798) debe devolver "DCCXCVIII" + testString: 'assert.deepEqual(convertToRoman(798), "DCCXCVIII", "convertToRoman(798) should return "DCCXCVIII"");' + - text: convertToRoman(891) debe devolver "DCCCXCI" + testString: 'assert.deepEqual(convertToRoman(891), "DCCCXCI", "convertToRoman(891) should return "DCCCXCI"");' + - text: convertToRoman(1000) debe devolver "M" + testString: 'assert.deepEqual(convertToRoman(1000), "M", "convertToRoman(1000) should return "M"");' + - text: convertToRoman(1004) debe devolver "MIV" + testString: 'assert.deepEqual(convertToRoman(1004), "MIV", "convertToRoman(1004) should return "MIV"");' + - text: convertToRoman(1006) debe devolver "MVI" + testString: 'assert.deepEqual(convertToRoman(1006), "MVI", "convertToRoman(1006) should return "MVI"");' + - text: convertToRoman(1023) debe devolver "MXXIII" + testString: 'assert.deepEqual(convertToRoman(1023), "MXXIII", "convertToRoman(1023) should return "MXXIII"");' + - text: convertToRoman(2014) debe devolver "MMXIV" + testString: 'assert.deepEqual(convertToRoman(2014), "MMXIV", "convertToRoman(2014) should return "MMXIV"");' + - text: convertToRoman(3999) debe devolver "MMMCMXCIX" + testString: 'assert.deepEqual(convertToRoman(3999), "MMMCMXCIX", "convertToRoman(3999) should return "MMMCMXCIX"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function convertToRoman(num) { + return num; +} + +convertToRoman(36); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function convertToRoman(num) { + var ref = [['M', 1000], ['CM', 900], ['D', 500], ['CD', 400], ['C', 100], ['XC', 90], ['L', 50], ['XL', 40], ['X', 10], ['IX', 9], ['V', 5], ['IV', 4], ['I', 1]]; + var res = []; + ref.forEach(function(p) { + while (num >= p[1]) { + res.push(p[0]); + num -= p[1]; + } + }); + return res.join(''); +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.spanish.md new file mode 100644 index 0000000000..d70ca9d60f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator.spanish.md @@ -0,0 +1,121 @@ +--- +id: aff0395860f5d3034dc0bfc9 +title: Telephone Number Validator +localeTitle: Validador de números de teléfono +challengeType: 5 +isRequired: true +--- + +## Description +
    +Devuelva true si la cadena pasada parece un número de teléfono válido de EE. UU. +El usuario puede completar el campo del formulario de la forma que elija, siempre que tenga el formato de un número de EE. UU. Válido. Los siguientes son ejemplos de formatos válidos para números de EE. UU. (Consulte las siguientes pruebas para otras variantes): +
    555-555-5555
    (555)555-5555
    (555) 555-5555
    555 555 5555
    5555555555
    1 555 555 5555
    +Para este desafío, se te presentará una cadena como 800-692-7753 o 8oo-six427676;laskdjf . Su trabajo es validar o rechazar el número de teléfono de los EE. UU. En función de cualquier combinación de los formatos proporcionados anteriormente. El código de área es obligatorio. Si se proporciona el código de país, debe confirmar que el código de país es 1 . Devuelva true si la cadena es un número de teléfono de EE. UU. Válido; de lo contrario devuelve false . +Recuerda usar Read-Search-Ask si te atascas. Trate de emparejar el programa. Escribe tu propio código. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: telephoneCheck("555-555-5555") debe devolver un valor booleano. + testString: 'assert(typeof telephoneCheck("555-555-5555") === "boolean", "telephoneCheck("555-555-5555") should return a boolean.");' + - text: telephoneCheck("1 555-555-5555") debe devolver el valor verdadero. + testString: 'assert(telephoneCheck("1 555-555-5555") === true, "telephoneCheck("1 555-555-5555") should return true.");' + - text: telephoneCheck("1 (555) 555-5555") debe devolver verdadero. + testString: 'assert(telephoneCheck("1 (555) 555-5555") === true, "telephoneCheck("1 (555) 555-5555") should return true.");' + - text: telephoneCheck("5555555555") debe devolver verdadero. + testString: 'assert(telephoneCheck("5555555555") === true, "telephoneCheck("5555555555") should return true.");' + - text: telephoneCheck("555-555-5555") debe devolver verdadero. + testString: 'assert(telephoneCheck("555-555-5555") === true, "telephoneCheck("555-555-5555") should return true.");' + - text: telephoneCheck("(555)555-5555") debe devolver verdadero. + testString: 'assert(telephoneCheck("(555)555-5555") === true, "telephoneCheck("(555)555-5555") should return true.");' + - text: telephoneCheck("1(555)555-5555") debe devolver verdadero. + testString: 'assert(telephoneCheck("1(555)555-5555") === true, "telephoneCheck("1(555)555-5555") should return true.");' + - text: telephoneCheck("555-5555") debe devolver falso. + testString: 'assert(telephoneCheck("555-5555") === false, "telephoneCheck("555-5555") should return false.");' + - text: telephoneCheck("5555555") debe devolver falso. + testString: 'assert(telephoneCheck("5555555") === false, "telephoneCheck("5555555") should return false.");' + - text: telephoneCheck("1 555)555-5555") debe devolver falso. + testString: 'assert(telephoneCheck("1 555)555-5555") === false, "telephoneCheck("1 555)555-5555") should return false.");' + - text: telephoneCheck("1 555 555 5555") debe devolver verdadero. + testString: 'assert(telephoneCheck("1 555 555 5555") === true, "telephoneCheck("1 555 555 5555") should return true.");' + - text: telephoneCheck("1 456 789 4444") debe devolver verdadero. + testString: 'assert(telephoneCheck("1 456 789 4444") === true, "telephoneCheck("1 456 789 4444") should return true.");' + - text: ' telephoneCheck("123**&!!asdf#") debe devolver falso.' + testString: 'assert(telephoneCheck("123**&!!asdf#") === false, "telephoneCheck("123**&!!asdf#") should return false.");' + - text: telephoneCheck("55555555") debe devolver falso. + testString: 'assert(telephoneCheck("55555555") === false, "telephoneCheck("55555555") should return false.");' + - text: telephoneCheck("(6054756961)") debe devolver falso + testString: 'assert(telephoneCheck("(6054756961)") === false, "telephoneCheck("(6054756961)") should return false");' + - text: telephoneCheck("2 (757) 622-7382") debe devolver falso. + testString: 'assert(telephoneCheck("2 (757) 622-7382") === false, "telephoneCheck("2 (757) 622-7382") should return false.");' + - text: telephoneCheck("0 (757) 622-7382") debe devolver falso. + testString: 'assert(telephoneCheck("0 (757) 622-7382") === false, "telephoneCheck("0 (757) 622-7382") should return false.");' + - text: telephoneCheck("-1 (757) 622-7382") debe devolver falso + testString: 'assert(telephoneCheck("-1 (757) 622-7382") === false, "telephoneCheck("-1 (757) 622-7382") should return false");' + - text: telephoneCheck("2 757 622-7382") debe devolver falso. + testString: 'assert(telephoneCheck("2 757 622-7382") === false, "telephoneCheck("2 757 622-7382") should return false.");' + - text: telephoneCheck("10 (757) 622-7382") debe devolver falso. + testString: 'assert(telephoneCheck("10 (757) 622-7382") === false, "telephoneCheck("10 (757) 622-7382") should return false.");' + - text: telephoneCheck("27576227382") debe devolver falso. + testString: 'assert(telephoneCheck("27576227382") === false, "telephoneCheck("27576227382") should return false.");' + - text: telephoneCheck("(275)76227382") debe devolver falso. + testString: 'assert(telephoneCheck("(275)76227382") === false, "telephoneCheck("(275)76227382") should return false.");' + - text: telephoneCheck("2(757)6227382") debe devolver falso. + testString: 'assert(telephoneCheck("2(757)6227382") === false, "telephoneCheck("2(757)6227382") should return false.");' + - text: telephoneCheck("2(757)622-7382") debe devolver falso. + testString: 'assert(telephoneCheck("2(757)622-7382") === false, "telephoneCheck("2(757)622-7382") should return false.");' + - text: telephoneCheck("555)-555-5555") debe devolver falso. + testString: 'assert(telephoneCheck("555)-555-5555") === false, "telephoneCheck("555)-555-5555") should return false.");' + - text: telephoneCheck("(555-555-5555") debe devolver falso. + testString: 'assert(telephoneCheck("(555-555-5555") === false, "telephoneCheck("(555-555-5555") should return false.");' + - text: telephoneCheck("(555)5(55?)-5555") debe devolver falso. + testString: 'assert(telephoneCheck("(555)5(55?)-5555") === false, "telephoneCheck("(555)5(55?)-5555") should return false.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function telephoneCheck(str) { + // Good luck! + return true; +} + +telephoneCheck("555-555-5555"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var re = /^([+]?1[\s]?)?((?:[(](?:[2-9]1[02-9]|[2-9][02-8][0-9])[)][\s]?)|(?:(?:[2-9]1[02-9]|[2-9][02-8][0-9])[\s.-]?)){1}([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2}[\s.-]?){1}([0-9]{4}){1}$/; + +function telephoneCheck(str) { + return re.test(str); +} + +telephoneCheck("555-555-5555"); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.spanish.md new file mode 100644 index 0000000000..8e9b02db72 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/add-methods-after-inheritance.spanish.md @@ -0,0 +1,94 @@ +--- +id: 587d7db1367417b2b2512b87 +title: Add Methods After Inheritance +localeTitle: Añadir métodos después de la herencia +challengeType: 1 +--- + +## Description +
    +Una función constructora que hereda su objeto prototype de una función constructora de supertype aún puede tener sus propios métodos además de los métodos heredados. +Por ejemplo, Bird es un constructor que hereda su prototype de Animal : +
    function Animal() { }
    Animal.prototype.eat = function() {
      console.log("nom nom nom");
    };
    function Bird() { }
    Bird.prototype = Object.create(Animal.prototype);
    Bird.prototype.constructor = Bird;
    +Además de lo que se hereda de Animal , desea agregar un comportamiento que sea único para los objetos Bird . Aquí, Bird obtendrá una función fly() . Las funciones se agregan al prototype Bird's la misma manera que cualquier función de constructor: +
    Bird.prototype.fly = function() {
      console.log("I'm flying!");
    };
    +Ahora, las instancias de Bird tendrán los métodos eat() y fly() : +
    let duck = new Bird();
    duck.eat(); // prints "nom nom nom"
    duck.fly(); // prints "I'm flying!"
    +
    + +## Instructions +
    +Agregue todo el código necesario para que el objeto Dog hereda de Animal y el constructor Dog's prototype Dog's esté configurado en Dog. Luego, agregue un método de bark() al objeto Dog para que el beagle pueda eat() y bark() . El método de la bark() debe imprimir "¡Guau!" a la consola. +
    + +## Tests +
    + +```yml +tests: + - text: Animal no debe responder al método de la bark() . + testString: 'assert(typeof Animal.prototype.bark == "undefined", "Animal should not respond to the bark() method.");' + - text: Dog debe heredar el método de eat() de Animal . + testString: 'assert(typeof Dog.prototype.eat == "function", "Dog should inherit the eat() method from Animal.");' + - text: Dog debe tener el método de la bark() como propiedad own . + testString: 'assert(Dog.prototype.hasOwnProperty("bark"), "Dog should have the bark() method as an own property.");' + - text: beagle debe ser un instanceof Animal . + testString: 'assert(beagle instanceof Animal, "beagle should be an instanceof Animal.");' + - text: El constructor para beagle debe establecer en Dog . + testString: 'assert(beagle.constructor === Dog, "The constructor for beagle should be set to Dog.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Animal() { } +Animal.prototype.eat = function() { console.log("nom nom nom"); }; + +function Dog() { } + +// Add your code below this line + + + + +// Add your code above this line + +let beagle = new Dog(); + +beagle.eat(); // Should print "nom nom nom" +beagle.bark(); // Should print "Woof!" +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Animal() { } +Animal.prototype.eat = function() { console.log("nom nom nom"); }; + +function Dog() { } +Dog.prototype = Object.create(Animal.prototype); +Dog.prototype.constructor = Dog; +Dog.prototype.bark = function () { + console.log('Woof!'); +}; +let beagle = new Dog(); + +beagle.eat(); +beagle.bark(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.spanish.md new file mode 100644 index 0000000000..e2180ea755 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/change-the-prototype-to-a-new-object.spanish.md @@ -0,0 +1,82 @@ +--- +id: 587d7daf367417b2b2512b7f +title: Change the Prototype to a New Object +localeTitle: Cambia el prototipo a un nuevo objeto +challengeType: 1 +--- + +## Description +
    +Hasta ahora ha estado agregando propiedades al prototype individualmente: +
    Bird.prototype.numLegs = 2;
    +Esto se vuelve tedioso después de más de unas pocas propiedades. +
    Bird.prototype.eat = function() {
      console.log("nom nom nom");
    }

    Bird.prototype.describe = function() {
      console.log("My name is " + this.name);
    }
    +Una forma más eficiente es establecer el prototype en un nuevo objeto que ya contenga las propiedades. De esta manera, las propiedades se agregan todas a la vez: +
    Bird.prototype = {
      numLegs: 2,
      eat: function() {
        console.log("nom nom nom");
      },
      describe: function() {
        console.log("My name is " + this.name);
      }
    };
    +
    + +## Instructions +
    +Agregue la propiedad numLegs y los dos métodos eat() y describe() al prototype de Dog estableciendo el prototype a un nuevo objeto. +
    + +## Tests +
    + +```yml +tests: + - text: Dog.prototype debe establecer en un nuevo objeto. + testString: 'assert((/Dog\.prototype\s*?=\s*?{/).test(code), "Dog.prototype should be set to a new object.");' + - text: Dog.prototype debe tener la propiedad numLegs . + testString: 'assert(Dog.prototype.numLegs !== undefined, "Dog.prototype should have the property numLegs.");' + - text: Dog.prototype debe tener el método eat() . + testString: 'assert(typeof Dog.prototype.eat === "function", "Dog.prototype should have the method eat()."); ' + - text: Dog.prototype debe tener el método describe() . + testString: 'assert(typeof Dog.prototype.describe === "function", "Dog.prototype should have the method describe()."); ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +Dog.prototype = { + // Add your code below this line + +}; +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} +Dog.prototype = { +numLegs: 4, + eat () { + console.log('nom nom nom'); + }, + describe () { + console.log('My name is ' + this.name); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.spanish.md new file mode 100644 index 0000000000..a7fe334148 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-basic-javascript-object.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d7dac367417b2b2512b73 +title: Create a Basic JavaScript Object +localeTitle: Crear un objeto JavaScript básico +challengeType: 1 +--- + +## Description +
    +Piense en cosas que la gente ve todos los días, como automóviles, tiendas y pájaros. Estos son todos los objects : cosas tangibles que las personas pueden observar e interactuar. +¿Cuáles son algunas de las cualidades de estos objects ? Un coche tiene ruedas. Las tiendas venden artículos. Las aves tienen alas. +Estas cualidades, o properties , definen lo que constituye un object . Tenga en cuenta que los objects similares comparten las mismas properties , pero pueden tener valores diferentes para esas properties . Por ejemplo, todos los autos tienen ruedas, pero no todos los autos tienen la misma cantidad de ruedas. +Objects en JavaScript se utilizan para modelar objetos del mundo real, dándoles properties y comportamiento al igual que sus contrapartes del mundo real. Aquí hay un ejemplo que usa estos conceptos para crear un object duck : +
    let duck = {
      name: "Aflac",
      numLegs: 2
    };
    +Este object duck tiene dos pares de propiedades / valores: un name de "Aflac" y un numLegs de 2. +
    + +## Instructions +
    +Crea un object dog con el name y numLegs propiedades numLegs , y numLegs en una cadena y un número, respectivamente. +
    + +## Tests +
    + +```yml +tests: + - text: dog debe ser un object . + testString: 'assert(typeof(dog) === "object", "dog should be an object.");' + - text: dog debería tener una propiedad de name establecida en una string . + testString: 'assert(typeof(dog.name) === "string", "dog should have a name property set to a string.");' + - text: dog debería tener una propiedad numLegs establecida en un number . + testString: 'assert(typeof(dog.numLegs) === "number", "dog should have a numLegs property set to a number.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let dog = { + +}; +``` + +
    + + + +
    + +## Solution +
    + + +```js +let dog = { + name: ", + numLegs: 4 +}; +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.spanish.md new file mode 100644 index 0000000000..32fdc3dd71 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/create-a-method-on-an-object.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7dad367417b2b2512b75 +title: Create a Method on an Object +localeTitle: Crear un método en un objeto +challengeType: 1 +--- + +## Description +
    +Objects pueden tener un tipo especial de property , llamado method . +Methods son properties que son funciones. Esto agrega un comportamiento diferente a un object . Aquí está el ejemplo de duck con un método: +
    let duck = {
      name: "Aflac",
      numLegs: 2,
      sayName: function() {return "The name of this duck is " + duck.name + ".";}
    };
    duck.sayName();
    // Returns "The name of this duck is Aflac."
    +El ejemplo agrega el method sayName , que es una función que devuelve una oración que da el nombre del duck . +Observe que el method accedió a la propiedad de name en la declaración de retorno usando duck.name . El próximo desafío cubrirá otra forma de hacer esto. +
    + +## Instructions +
    +Usando el object dog , dale un método llamado sayLegs . El método debe devolver la frase "Este perro tiene 4 patas". +
    + +## Tests +
    + +```yml +tests: + - text: dog.sayLegs() debería ser una función. + testString: 'assert(typeof(dog.sayLegs) === "function", "dog.sayLegs() should be a function.");' + - text: dog.sayLegs() debe devolver la cadena dada; tenga en cuenta que la puntuación y el espaciado son importantes. + testString: 'assert(dog.sayLegs() === "This dog has 4 legs.", "dog.sayLegs() should return the given string - note that punctuation and spacing matter.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let dog = { + name: "Spot", + numLegs: 4, + +}; + +dog.sayLegs(); +``` + +
    + + + +
    + +## Solution +
    + + +```js +let dog = { + name: "Spot", + numLegs: 4, + sayLegs () { + return 'This dog has ' + this.numLegs + ' legs.'; + } +}; + +dog.sayLegs(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.spanish.md new file mode 100644 index 0000000000..49f5ccb72e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/define-a-constructor-function.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d7dad367417b2b2512b77 +title: Define a Constructor Function +localeTitle: Definir una función de constructor +challengeType: 1 +--- + +## Description +
    +Constructors son funciones que crean nuevos objetos. Definen propiedades y comportamientos que pertenecerán al nuevo objeto. Piense en ellos como un plano para la creación de nuevos objetos. +Aquí hay un ejemplo de un constructor : +
    function Bird() {
      this.name = "Albert";
      this.color = "blue";
      this.numLegs = 2;
    }
    +Este constructor define un objeto Bird con el name , el color y las numLegs establecidas en Albert, azul y 2, respectivamente. +Constructors siguen algunas convenciones: +
    • Constructors se definen con un nombre en mayúsculas para distinguirlos de otras funciones que no son constructors .
    • Constructors usan la palabra clave this para establecer las propiedades del objeto que crearán. Dentro del constructor , this refiere al nuevo objeto que creará.
    • Constructors definen propiedades y comportamientos en lugar de devolver un valor como otras funciones podrían.
    +
    + +## Instructions +
    +Cree un constructor , Dog , con las propiedades name , color y numLegs que se establecen en una cadena, una cadena y un número, respectivamente. +
    + +## Tests +
    + +```yml +tests: + - text: Dog debe tener una propiedad de name establecida en una cadena. + testString: 'assert(typeof (new Dog()).name === "string", "Dog should have a name property set to a string.");' + - text: Dog debe tener una propiedad de color establecida en una cadena. + testString: 'assert(typeof (new Dog()).color === "string", "Dog should have a color property set to a string.");' + - text: Dog debe tener una propiedad numLegs establecida en un número. + testString: 'assert(typeof (new Dog()).numLegs === "number", "Dog should have a numLegs property set to a number.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog (name, color, numLegs) { + this.name = 'name'; + this.color = 'color'; + this.numLegs = 4; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.spanish.md new file mode 100644 index 0000000000..79b9bd7490 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/extend-constructors-to-receive-arguments.spanish.md @@ -0,0 +1,79 @@ +--- +id: 587d7dae367417b2b2512b79 +title: Extend Constructors to Receive Arguments +localeTitle: Extender constructores para recibir argumentos +challengeType: 1 +--- + +## Description +
    +Los constructores de Bird y Dog del último desafío funcionaron bien. Sin embargo, tenga en cuenta que todas las Birds que se crean con el constructor Bird se denominan automáticamente Albert, son de color azul y tienen dos patas. ¿Y si quieres pájaros con diferentes valores de nombre y color? Es posible cambiar las propiedades de cada ave manualmente, pero eso sería mucho trabajo: +
    let swan = new Bird();
    swan.name = "Carlos";
    swan.color = "white";
    +Suponga que estaba escribiendo un programa para realizar un seguimiento de cientos o incluso miles de aves diferentes en una pajarera. Tomaría mucho tiempo crear todas las aves, luego cambiar las propiedades a diferentes valores para cada una. +Para crear más fácilmente diferentes objetos Bird , puede diseñar su constructor Bird para que acepte parámetros: +
    function Bird(name, color) {
      this.name = name;
      this.color = color;
      this.numLegs = 2;
    }
    +Luego, pase los valores como argumentos para definir cada ave única en el constructor de Bird : +let cardinal = new Bird("Bruce", "red"); +Esto da una nueva instancia de Bird con las propiedades de nombre y color establecidas en Bruce y rojo, respectivamente. La propiedad numLegs todavía se establece en 2. +El cardinal tiene estas propiedades: +
    cardinal.name // => Bruce
    cardinal.color // => red
    cardinal.numLegs // => 2
    +El constructor es más flexible. Ahora es posible definir las propiedades de cada Bird en el momento de su creación, que es una forma en que los constructores de JavaScript son tan útiles. Agrupan los objetos en función de las características y el comportamiento compartidos y definen un plan que automatiza su creación. +
    + +## Instructions +
    +Crear otro constructor de Dog . Esta vez, numLegs para tomar el name y el color los parámetros, y numLegs que la propiedad numLegs fije en 4. Luego crea un nuevo Dog guardado en una variable terrier . Pásale dos cadenas como argumentos para las propiedades de name y color . +
    + +## Tests +
    + +```yml +tests: + - text: Dog debe recibir un argumento para su name . + testString: 'assert((new Dog("Clifford")).name === "Clifford", "Dog should receive an argument for name.");' + - text: Dog debe recibir un argumento para el color . + testString: 'assert((new Dog("Clifford", "yellow")).color === "yellow", "Dog should receive an argument for color.");' + - text: Dog debe tener la propiedad numLegs establecida en 4. + testString: 'assert((new Dog("Clifford")).numLegs === 4, "Dog should have property numLegs set to 4.");' + - text: terrier debe ser creado usando el constructor Dog . + testString: 'assert(terrier instanceof Dog, "terrier should be created using the Dog constructor.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog() { + +} + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog (name, color) { + this.numLegs = 4; + this.name = name; + this.color = color; +} + +const terrier = new Dog(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.spanish.md new file mode 100644 index 0000000000..500c96a9cc --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/inherit-behaviors-from-a-supertype.spanish.md @@ -0,0 +1,95 @@ +--- +id: 587d7db0367417b2b2512b84 +title: Inherit Behaviors from a Supertype +localeTitle: Heredar los comportamientos de un supertipo +challengeType: 1 +--- + +## Description +
    +En el desafío anterior, creaste un supertype llamado Animal que definía comportamientos compartidos por todos los animales: +
    function Animal() { }
    Animal.prototype.eat = function() {
      console.log("nom nom nom");
    };
    +Este y el próximo desafío abarcarán cómo reutilizar Animal's métodos Animal's dentro de Bird y Dog sin volver a definirlos. Utiliza una técnica llamada inheritance . +Este desafío cubre el primer paso: crear una instancia del supertype (o padre). +Ya conoces una forma de crear una instancia de Animal utilizando el new operador: +
    let animal = new Animal();
    +Existen algunas desventajas al usar esta sintaxis para inheritance , que son demasiado complejas para el alcance de este desafío. En cambio, aquí hay un enfoque alternativo sin esas desventajas: +
    let animal = Object.create(Animal.prototype);
    +Object.create(obj) crea un nuevo objeto y establece obj como el prototype del nuevo objeto. Recuerde que el prototype es como la "receta" para crear un objeto. Al configurar el prototype de animal para que sea Animal's prototype Animal's , le está dando efectivamente a la instancia animal la misma "receta" que cualquier otra instancia de Animal . +
    animal.eat(); // prints "nom nom nom"
    animal instanceof Animal; // => true
    +
    + +## Instructions +
    +Use Object.create para crear dos instancias de Animal llamado duck y beagle . +
    + +## Tests +
    + +```yml +tests: + - text: La variable duck debe estar definida. + testString: 'assert(typeof duck !== "undefined", "The duck variable should be defined.");' + - text: La variable beagle debe estar definida. + testString: 'assert(typeof beagle !== "undefined", "The beagle variable should be defined.");' + - text: duck debe tener un prototype de Animal . + testString: 'assert(duck instanceof Animal, "duck should have a prototype of Animal.");' + - text: beagle debe tener un prototype de Animal . + testString: 'assert(beagle instanceof Animal, "beagle should have a prototype of Animal.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Animal() { } + +Animal.prototype = { + constructor: Animal, + eat: function() { + console.log("nom nom nom"); + } +}; + +// Add your code below this line + +let duck; // Change this line +let beagle; // Change this line + +duck.eat(); // Should print "nom nom nom" +beagle.eat(); // Should print "nom nom nom" +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Animal() { } + +Animal.prototype = { + constructor: Animal, + eat: function() { + console.log("nom nom nom"); + } +}; +let duck = Object.create(Animal.prototype); +let beagle = Object.create(Animal.prototype); + +duck.eat(); +beagle.eat(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.spanish.md new file mode 100644 index 0000000000..026c63365b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/iterate-over-all-properties.spanish.md @@ -0,0 +1,90 @@ +--- +id: 587d7daf367417b2b2512b7d +title: Iterate Over All Properties +localeTitle: Iterar sobre todas las propiedades +challengeType: 1 +--- + +## Description +
    +Ahora ha visto dos tipos de propiedades: propiedades own y propiedades de prototype . Own propiedades Own se definen directamente en la instancia del objeto en sí. Y las propiedades del prototype se definen en el prototype . +
    function Bird(name) {
      this.name = name; //own property
    }

    Bird.prototype.numLegs = 2; // prototype property

    let duck = new Bird("Donald");
    +Así es como se agregan duck's propiedades own duck's a la matriz ownProps y las propiedades de prototype a la matriz prototypeProps : +
    let ownProps = [];
    let prototypeProps = [];

    for (let property in duck) {
      if(duck.hasOwnProperty(property)) {
        ownProps.push(property);
      } else {
        prototypeProps.push(property);
      }
    }

    console.log(ownProps); // prints ["name"]
    console.log(prototypeProps); // prints ["numLegs"]
    +
    + +## Instructions +
    +Agregue todas las propiedades own de beagle a la matriz ownProps . Agregue todas las propiedades prototype de Dog a la matriz prototypeProps . +
    + +## Tests +
    + +```yml +tests: + - text: La matriz ownProps debe incluir "name" . + testString: 'assert(ownProps.indexOf("name") !== -1, "The ownProps array should include "name".");' + - text: La matriz prototypeProps debe incluir "numLegs" . + testString: 'assert(prototypeProps.indexOf("numLegs") !== -1, "The prototypeProps array should include "numLegs".");' + - text: Resuelva este desafío sin usar el método Object.keys() . + testString: 'assert(!/\Object.keys/.test(code), "Solve this challenge without using the built in method Object.keys().");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +Dog.prototype.numLegs = 4; + +let beagle = new Dog("Snoopy"); + +let ownProps = []; +let prototypeProps = []; + +// Add your code below this line + + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} + +Dog.prototype.numLegs = 4; + +let beagle = new Dog("Snoopy"); + +let ownProps = []; +let prototypeProps = []; +for (let prop in beagle) { + if (beagle.hasOwnProperty(prop)) { + ownProps.push(prop); + } else { + prototypeProps.push(prop); + } +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.spanish.md new file mode 100644 index 0000000000..9d459ebf2d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/make-code-more-reusable-with-the-this-keyword.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7dad367417b2b2512b76 +title: Make Code More Reusable with the this Keyword +localeTitle: Hacer el código más reutilizable con la palabra clave +challengeType: 1 +--- + +## Description +
    +El último desafío introdujo un method para el objeto duck . duck.name la notación de puntos duck.name para acceder al valor de la propiedad name dentro de la declaración de retorno: +sayName: function() {return "The name of this duck is " + duck.name + ".";} +Mientras está una forma válida de acceder a la propiedad del objeto, aquí hay un escollo. Si el nombre de la variable cambia, también se deberá actualizar cualquier código que haga referencia al nombre original. En una definición de objeto breve, no es un problema, pero si un objeto tiene muchas referencias a sus propiedades, existe una mayor posibilidad de error. +Una forma de evitar estos problemas es con this palabra clave: +
    let duck = {
      name: "Aflac",
      numLegs: 2,
      sayName: function() {return "The name of this duck is " + this.name + ".";}
    };
    +this es un tema profundo, y el ejemplo anterior es solo una forma de usarlo. En el contexto actual, this refiere al objeto con el que el método está asociado: duck . +Si el nombre del objeto se cambia a mallard , no es necesario encontrar todas las referencias a duck en el código. Hace que el código sea reutilizable y más fácil de leer. +
    + +## Instructions +
    +Modifique el método dog.sayLegs para eliminar cualquier referencia a dog . Utilice el ejemplo de duck para orientación. +
    + +## Tests +
    + +```yml +tests: + - text: dog.sayLegs() debe devolver la cadena dada. + testString: 'assert(dog.sayLegs() === "This dog has 4 legs.", "dog.sayLegs() should return the given string.");' + - text: Su código debe usar this palabra clave para acceder a la propiedad numLegs de dog . + testString: 'assert(code.match(/this\.numLegs/g), "Your code should use the this keyword to access the numLegs property of dog.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let dog = { + name: "Spot", + numLegs: 4, + sayLegs: function() {return "This dog has " + dog.numLegs + " legs.";} +}; + +dog.sayLegs(); +``` + +
    + + + +
    + +## Solution +
    + + +```js +let dog = { + name: "Spot", + numLegs: 4, + sayLegs () { + return 'This dog has ' + this.numLegs + ' legs.'; + } +}; + +dog.sayLegs(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.spanish.md new file mode 100644 index 0000000000..df065d5295 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods.spanish.md @@ -0,0 +1,90 @@ +--- +id: 587d7db1367417b2b2512b88 +title: Override Inherited Methods +localeTitle: Anular métodos heredados +challengeType: 1 +--- + +## Description +
    +En las lecciones anteriores, aprendió que un objeto puede heredar su comportamiento (métodos) de otro objeto clonando su objeto prototype : +
    ChildObject.prototype = Object.create(ParentObject.prototype);
    +Luego, ChildObject recibió sus propios métodos al encadenarlos a su prototype : +
    ChildObject.prototype.methodName = function() {...};
    +Es posible anular un método heredado. Se realiza de la misma manera: agregando un método a ChildObject.prototype utilizando el mismo nombre de método que el que se anula. +Este es un ejemplo de Bird anula el método eat() heredado de Animal : +
    function Animal() { }
    Animal.prototype.eat = function() {
      return "nom nom nom";
    };
    function Bird() { }

    // Inherit all methods from Animal
    Bird.prototype = Object.create(Animal.prototype);

    // Bird.eat() overrides Animal.eat()
    Bird.prototype.eat = function() {
      return "peck peck peck";
    };
    +Si tienes una instancia, let duck = new Bird(); y llama a duck.eat() , así es como JavaScript busca el método en duck's cadena de prototype duck's : +1. duck => ¿Se define eat () aquí? No. +2. Pájaro => ¿Se define eat () aquí? => Sí. Ejecutarlo y dejar de buscar. +3. Animal => eat () también está definido, pero JavaScript dejó de buscar antes de alcanzar este nivel. +4. Objeto => JavaScript dejó de buscar antes de alcanzar este nivel. +
    + +## Instructions +
    +Anula el método fly() de Penguin para que devuelva "¡Ay !, este es un pájaro que no vuela". +
    + +## Tests +
    + +```yml +tests: + - text: ' penguin.fly() debería devolver la cadena "¡Ay !, este es un pájaro que no vuela». + testString: 'assert(penguin.fly() === "Alas, this is a flightless bird.", "penguin.fly() should return the string "Alas, this is a flightless bird."");' + - text: El método bird.fly() debería devolver "Estoy volando!" + testString: 'assert((new Bird()).fly() === "I am flying!", "The bird.fly() method should return "I am flying!"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Bird() { } + +Bird.prototype.fly = function() { return "I am flying!"; }; + +function Penguin() { } +Penguin.prototype = Object.create(Bird.prototype); +Penguin.prototype.constructor = Penguin; + +// Add your code below this line + + + +// Add your code above this line + +let penguin = new Penguin(); +console.log(penguin.fly()); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Bird() { } + +Bird.prototype.fly = function() { return "I am flying!"; }; + +function Penguin() { } +Penguin.prototype = Object.create(Bird.prototype); +Penguin.prototype.constructor = Penguin; +Penguin.prototype.fly = () => 'Alas, this is a flightless bird.'; +let penguin = new Penguin(); +console.log(penguin.fly()); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.spanish.md new file mode 100644 index 0000000000..f3bb202dad --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.spanish.md @@ -0,0 +1,82 @@ +--- +id: 587d7daf367417b2b2512b80 +title: Remember to Set the Constructor Property when Changing the Prototype +localeTitle: Recuerde establecer la propiedad del constructor al cambiar el prototipo +challengeType: 1 +--- + +## Description +
    +Hay un efecto secundario crucial de configurar manualmente el prototype en un nuevo objeto. Se borró la propiedad del constructor ! El código del desafío anterior imprimirá lo siguiente para el duck : +
    console.log(duck.constructor)
    // prints ‘undefined’ - Oops!
    +Para solucionar este problema, siempre que un prototipo se establezca manualmente en un nuevo objeto, recuerde definir la propiedad del constructor : +
    Bird.prototype = {
      constructor: Bird, // define the constructor property
      numLegs: 2,
      eat: function() {
        console.log("nom nom nom");
      },
      describe: function() {
        console.log("My name is " + this.name);
      }
    };
    +
    + +## Instructions +
    +Defina la propiedad del constructor en el prototype Dog . +
    + +## Tests +
    + +```yml +tests: + - text: Dog.prototype debería establecer la propiedad del constructor . + testString: 'assert(Dog.prototype.constructor === Dog, "Dog.prototype should set the constructor property.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +// Modify the code below this line +Dog.prototype = { + + numLegs: 2, + eat: function() { + console.log("nom nom nom"); + }, + describe: function() { + console.log("My name is " + this.name); + } +}; +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} +Dog.prototype = { + constructor: Dog, + numLegs: 2, + eat: function() { + console.log("nom nom nom"); + }, + describe: function() { + console.log("My name is " + this.name); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.spanish.md new file mode 100644 index 0000000000..0ab20e3b76 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/reset-an-inherited-constructor-property.spanish.md @@ -0,0 +1,83 @@ +--- +id: 587d7db1367417b2b2512b86 +title: Reset an Inherited Constructor Property +localeTitle: Restablecer una propiedad de constructor heredada +challengeType: 1 +--- + +## Description +
    +Cuando un objeto hereda su prototype de otro objeto, sino que también hereda el supertype propiedad constructor 's. +Aquí hay un ejemplo: +
    function Bird() { }
    Bird.prototype = Object.create(Animal.prototype);
    let duck = new Bird();
    duck.constructor // function Animal(){...}
    +Pero el duck y todos los casos de Bird deben mostrar que fueron construidos por Bird y no por Animal . Para hacerlo, puedes establecer manualmente Bird's propiedad Bird's constructor de Bird objeto Bird : +
    Bird.prototype.constructor = Bird;
    duck.constructor // function Bird(){...}
    +
    + +## Instructions +
    +duck.constructor el código para que duck.constructor y beagle.constructor devuelvan sus respectivos constructores. +
    + +## Tests +
    + +```yml +tests: + - text: Bird.prototype debe ser una instancia de Animal . + testString: 'assert(Animal.prototype.isPrototypeOf(Bird.prototype), "Bird.prototype should be an instance of Animal.");' + - text: duck.constructor debe devolver Bird . + testString: 'assert(duck.constructor === Bird, "duck.constructor should return Bird.");' + - text: Dog.prototype debe ser una instancia de Animal . + testString: 'assert(Animal.prototype.isPrototypeOf(Dog.prototype), "Dog.prototype should be an instance of Animal.");' + - text: beagle.constructor debe devolver el Dog . + testString: 'assert(beagle.constructor === Dog, "beagle.constructor should return Dog.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Animal() { } +function Bird() { } +function Dog() { } + +Bird.prototype = Object.create(Animal.prototype); +Dog.prototype = Object.create(Animal.prototype); + +// Add your code below this line + + + +let duck = new Bird(); +let beagle = new Dog(); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Animal() { } +function Bird() { } +function Dog() { } +Bird.prototype = Object.create(Animal.prototype); +Dog.prototype = Object.create(Animal.prototype); +Dog.prototype.constructor = Dog; +Bird.prototype.constructor = Bird; +let duck = new Bird(); +let beagle = new Dog(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.spanish.md new file mode 100644 index 0000000000..ee131e1d7f --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/set-the-childs-prototype-to-an-instance-of-the-parent.spanish.md @@ -0,0 +1,86 @@ +--- +id: 587d7db1367417b2b2512b85 +title: Set the Child's Prototype to an Instance of the Parent +localeTitle: Establecer el prototipo del niño en una instancia del padre +challengeType: 1 +--- + +## Description +
    +En el desafío anterior, vio el primer paso para heredar el comportamiento del supertype (o padre) Animal : crear una nueva instancia de Animal . +Este desafío cubre el siguiente paso: configurar el prototype del subtype (o niño), en este caso, Bird , para que sea una instancia de Animal . +
    Bird.prototype = Object.create(Animal.prototype);
    +Recuerde que el prototype es como la "receta" para crear un objeto. En cierto modo, la receta para Bird ahora incluye todos los "ingredientes" clave de Animal . +
    let duck = new Bird("Donald");
    duck.eat(); // prints "nom nom nom"
    +duck hereda todas las propiedades de los Animal , incluido el método de eat . +
    + +## Instructions +
    +Modificar el código para que las instancias de Dog hereden de Animal . +
    + +## Tests +
    + +```yml +tests: + - text: Dog.prototype debe ser una instancia de Animal . + testString: 'assert(Animal.prototype.isPrototypeOf(Dog.prototype), "Dog.prototype should be an instance of Animal.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Animal() { } + +Animal.prototype = { + constructor: Animal, + eat: function() { + console.log("nom nom nom"); + } +}; + +function Dog() { } + +// Add your code below this line + + +let beagle = new Dog(); +beagle.eat(); // Should print "nom nom nom" +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Animal() { } + +Animal.prototype = { + constructor: Animal, + eat: function() { + console.log("nom nom nom"); + } +}; + +function Dog() { } +Dog.prototype = Object.create(Animal.prototype); + +let beagle = new Dog(); +beagle.eat(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.spanish.md new file mode 100644 index 0000000000..a61c3c5915 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-own-properties.spanish.md @@ -0,0 +1,88 @@ +--- +id: 587d7dae367417b2b2512b7b +title: Understand Own Properties +localeTitle: Entender propiedades propias +challengeType: 1 +--- + +## Description +
    +En el siguiente ejemplo, el constructor de Bird define dos propiedades: name y numLegs : +
    function Bird(name) {
      this.name = name;
      this.numLegs = 2;
    }

    let duck = new Bird("Donald");
    let canary = new Bird("Tweety");
    +name y numLegs se denominan propiedades own , porque se definen directamente en el objeto de instancia. Eso significa que el duck y el canary tienen su propia copia separada de estas propiedades. +De hecho, cada instancia de Bird tendrá su propia copia de estas propiedades. +El siguiente código agrega todas las propiedades own de duck a la matriz ownProps : +
    let ownProps = [];

    for (let property in duck) {
      if(duck.hasOwnProperty(property)) {
        ownProps.push(property);
      }
    }

    console.log(ownProps); // prints [ "name", "numLegs" ]
    +
    + +## Instructions +
    +Agrega las propiedades own de canary a la matriz ownProps . +
    + +## Tests +
    + +```yml +tests: + - text: ownProps debe incluir los valores "numLegs" y "name" . + testString: 'assert(ownProps.indexOf("name") !== -1 && ownProps.indexOf("numLegs") !== -1, "ownProps should include the values "numLegs" and "name".");' + - text: Resuelva este desafío sin usar el método Object.keys() . + testString: 'assert(!/\Object.keys/.test(code), "Solve this challenge without using the built in method Object.keys().");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Bird(name) { + this.name = name; + this.numLegs = 2; +} + +let canary = new Bird("Tweety"); +let ownProps = []; +// Add your code below this line + + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Bird(name) { + this.name = name; + this.numLegs = 2; +} + +let canary = new Bird("Tweety"); +function getOwnProps (obj) { + const props = []; + + for (let prop in obj) { + if (obj.hasOwnProperty(prop)) { + props.push(prop); + } + } + + return props; +} + +const ownProps = getOwnProps(canary); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.spanish.md new file mode 100644 index 0000000000..1bc4b8d639 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-constructor-property.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7daf367417b2b2512b7e +title: Understand the Constructor Property +localeTitle: Entender la propiedad del constructor +challengeType: 1 +--- + +## Description +
    +Hay una propiedad de constructor especial ubicada en las instancias de objeto duck y beagle que se crearon en los desafíos anteriores: +
    let duck = new Bird();
    let beagle = new Dog();

    console.log(duck.constructor === Bird); //prints true
    console.log(beagle.constructor === Dog); //prints true
    +Tenga en cuenta que la propiedad del constructor es una referencia a la función del constructor que creó la instancia. +La ventaja de la propiedad del constructor es que es posible verificar esta propiedad para saber qué tipo de objeto es. Aquí hay un ejemplo de cómo se podría usar: +
    function joinBirdFraternity(candidate) {
      if (candidate.constructor === Bird) {
        return true;
      } else {
        return false;
      }
    }
    +Nota
    Dado que la propiedad del constructor se puede sobrescribir (que se cubrirá en los siguientes dos desafíos), generalmente es mejor usar el método instanceof para verificar el tipo de un objeto. +
    + +## Instructions +
    +Escriba una función joinDogFraternity que tome un parámetro candidate y, utilizando la propiedad del constructor , devuelva true si el candidato es un Dog , de lo contrario, devuelva false . +
    + +## Tests +
    + +```yml +tests: + - text: joinDogFraternity debe definirse como una función. + testString: 'assert(typeof(joinDogFraternity) === "function", "joinDogFraternity should be defined as a function.");' + - text: joinDogFraternity debería devolver true si el candidate es una instancia de Dog . + testString: 'assert(joinDogFraternity(new Dog("")) === true, "joinDogFraternity should return true ifcandidate is an instance of Dog.");' + - text: joinDogFraternity debe usar la propiedad del constructor . + testString: 'assert(/\.constructor/.test(code) && !/instanceof/.test(code), "joinDogFraternity should use the constructor property.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +// Add your code below this line +function joinDogFraternity(candidate) { + +} + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} +function joinDogFraternity(candidate) { + return candidate.constructor === Dog; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.spanish.md new file mode 100644 index 0000000000..fd1b3c4038 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-immediately-invoked-function-expression-iife.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7db2367417b2b2512b8b +title: Understand the Immediately Invoked Function Expression (IIFE) +localeTitle: Comprender la expresión de función invocada inmediatamente (IIFE) +challengeType: 1 +--- + +## Description +
    +Un patrón común en JavaScript es ejecutar una función tan pronto como se declara: +
    (function () {
      console.log("Chirp, chirp!");
    })(); // this is an anonymous function expression that executes right away
    // Outputs "Chirp, chirp!" immediately
    +Tenga en cuenta que la función no tiene nombre y no está almacenada en una variable. Los dos paréntesis () al final de la expresión de la función hacen que se ejecute o se invoque inmediatamente. Este patrón se conoce como una immediately invoked function expression o IIFE . +
    + +## Instructions +
    +Reescriba la función makeNest y elimine su llamada, por lo que es una immediately invoked function expression forma anónima ( IIFE ). +
    + +## Tests +
    + +```yml +tests: + - text: La función debe ser anónima. + testString: 'assert(/\(\s*?function\s*?\(\s*?\)\s*?{/.test(code), "The function should be anonymous.");' + - text: Su función debe tener paréntesis al final de la expresión para llamarla inmediatamente. + testString: 'assert(/}\s*?\)\s*?\(\s*?\)/.test(code), "Your function should have parentheses at the end of the expression to call it immediately.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function makeNest() { + console.log("A cozy nest is ready"); +} + +makeNest(); +``` + +
    + + + +
    + +## Solution +
    + + +```js +(function () { + console.log("A cozy nest is ready"); +})(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.spanish.md new file mode 100644 index 0000000000..b3f0961241 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-the-prototype-chain.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d7db0367417b2b2512b82 +title: Understand the Prototype Chain +localeTitle: Entender la cadena de prototipos +challengeType: 1 +--- + +## Description +
    +Todos los objetos en JavaScript (con algunas excepciones) tienen un prototype . Además, el prototype un objeto en sí mismo es un objeto. +
    function Bird(name) {
      this.name = name;
    }

    typeof Bird.prototype; // => object
    +Debido a que un prototype es un objeto, ¡un prototype puede tener su propio prototype ! En este caso, el prototype de Bird.prototype es Object.prototype : +
    Object.prototype.isPrototypeOf(Bird.prototype);
    // returns true
    +¿Cómo es esto útil? Puede recordar el método hasOwnProperty de un desafío anterior: +
    let duck = new Bird("Donald");
    duck.hasOwnProperty("name"); // => true
    +El método hasOwnProperty se define en Object.prototype , al que se puede acceder mediante Bird.prototype , al que luego se puede acceder mediante duck . Este es un ejemplo de la cadena prototype . +En esta cadena prototype , Bird es el supertype para el duck , mientras que el duck es el subtype . Object es un supertype tanto para Bird como para duck . +Object es un supertype para todos los objetos en JavaScript. Por lo tanto, cualquier objeto puede usar el método hasOwnProperty . +
    + +## Instructions +
    +Modificar el código para mostrar la cadena de prototipo correcta. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe mostrar que Object.prototype es el prototipo de Dog.prototype ") + testString: 'assert(/Object\.prototype\.isPrototypeOf/.test(code), "Your code should show that Object.prototype is the prototype of Dog.prototype");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +let beagle = new Dog("Snoopy"); + +Dog.prototype.isPrototypeOf(beagle); // => true + +// Fix the code below so that it evaluates to true +???.isPrototypeOf(Dog.prototype); + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} +let beagle = new Dog("Snoopy"); +Dog.prototype.isPrototypeOf(beagle); +Object.prototype.isPrototypeOf(Dog.prototype); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.spanish.md new file mode 100644 index 0000000000..c16044a7f4 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/understand-where-an-objects-prototype-comes-from.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7db0367417b2b2512b81 +title: Understand Where an Object’s Prototype Comes From +localeTitle: Entender de dónde viene el prototipo de un objeto +challengeType: 1 +--- + +## Description +
    +Al igual que las personas heredan genes de sus padres, un objeto hereda su prototype directamente de la función constructora que lo creó. Por ejemplo, aquí el constructor Bird crea el objeto duck : +
    function Bird(name) {
      this.name = name;
    }

    let duck = new Bird("Donald");
    +duck hereda su prototype de la función constructor de Bird . Puede mostrar esta relación con el método isPrototypeOf : +
    Bird.prototype.isPrototypeOf(duck);
    // returns true
    +
    + +## Instructions +
    +Usa isPrototypeOf para verificar el prototype de beagle . +
    + +## Tests +
    + +```yml +tests: + - text: Mostrar que Dog.prototype es el prototype de beagle + testString: 'assert(/Dog\.prototype\.isPrototypeOf\(beagle\)/.test(code), "Show that Dog.prototype is the prototype of beagle");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + +let beagle = new Dog("Snoopy"); + +// Add your code below this line + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog(name) { + this.name = name; +} +let beagle = new Dog("Snoopy"); +Dog.prototype.isPrototypeOf(beagle); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.spanish.md new file mode 100644 index 0000000000..74aeff2f20 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-constructor-to-create-objects.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7dad367417b2b2512b78 +title: Use a Constructor to Create Objects +localeTitle: Usa un constructor para crear objetos +challengeType: 1 +--- + +## Description +
    +Aquí está el constructor Bird del desafío anterior: +
    function Bird() {
      this.name = "Albert";
      this.color = "blue";
      this.numLegs = 2;
      // "this" inside the constructor always refers to the object being created
    }

    let blueBird = new Bird();
    +Observe que el new operador se utiliza al llamar a un constructor. Esto le dice a JavaScript que cree una nueva instance de Bird llamada blueBird . Sin el new operador, this dentro del constructor no apuntaría al objeto recién creado, dando resultados inesperados. +Ahora, blueBird tiene todas las propiedades definidas dentro del constructor Bird : +
    blueBird.name; // => Albert
    blueBird.color; // => blue
    blueBird.numLegs; // => 2
    +Al igual que cualquier otro objeto, sus propiedades se pueden acceder y modificar: +
    blueBird.name = 'Elvira';
    blueBird.name; // => Elvira
    +
    + +## Instructions +
    +Usa el constructor Dog de la última lección para crear una nueva instancia de Dog , asignándola a un hound variable. +
    + +## Tests +
    + +```yml +tests: + - text: hound debe ser creado usando el constructor de Dog . + testString: 'assert(hound instanceof Dog, "hound should be created using the Dog constructor.");' + - text: Tu código debe usar el new operador para crear una instance de Dog . + testString: 'assert(code.match(/new/g), "Your code should use the new operator to create an instance of Dog.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog() { + this.name = "Rupert"; + this.color = "brown"; + this.numLegs = 4; +} +// Add your code below this line + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog() { + this.name = "Rupert"; + this.color = "brown"; + this.numLegs = 4; +} +const hound = new Dog(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.spanish.md new file mode 100644 index 0000000000..f58703f913 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-a-mixin-to-add-common-behavior-between-unrelated-objects.spanish.md @@ -0,0 +1,94 @@ +--- +id: 587d7db2367417b2b2512b89 +title: Use a Mixin to Add Common Behavior Between Unrelated Objects +localeTitle: Use un Mixin para agregar un comportamiento común entre objetos no relacionados +challengeType: 1 +--- + +## Description +
    +Como has visto, el comportamiento se comparte a través de la herencia. Sin embargo, hay casos en que la herencia no es la mejor solución. La herencia no funciona bien para objetos no relacionados como Bird y Airplane . Ambos pueden volar, pero un Bird no es un tipo de Airplane y viceversa. +Para objetos no relacionados, es mejor usar mixins . Una mixin permite que otros objetos usen una colección de funciones. +
    let flyMixin = function(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      }
    };
    +El flyMixin toma cualquier objeto y le da el método de fly . +
    let bird = {
      name: "Donald",
      numLegs: 2
    };

    let plane = {
      model: "777",
      numPassengers: 524
    };

    flyMixin(bird);
    flyMixin(plane);
    +Aquí las bird y el plane pasan a flyMixin , que luego asigna la función de fly a cada objeto. Ahora el bird y el plane pueden volar: +
    bird.fly(); // prints "Flying, wooosh!"
    plane.fly(); // prints "Flying, wooosh!"
    +Observe cómo la mixin permite que el mismo método de fly sea ​​reutilizado por objetos no relacionados, bird y plane . +
    + +## Instructions +
    +Crear un mixin llamado glideMixin que define un método llamado glide . Luego use el glideMixin para que tanto el bird como el boat puedan deslizarse. +
    + +## Tests +
    + +```yml +tests: + - text: Su código debe declarar una variable glideMixin que es una función. + testString: 'assert(typeof glideMixin === "function", "Your code should declare a glideMixin variable that is a function.");' + - text: Su código debe usar el glideMixin en el objeto bird para darle el método de glide . + testString: 'assert(typeof bird.glide === "function", "Your code should use the glideMixin on the bird object to give it the glide method.");' + - text: Su código debe usar el glideMixin en el objeto del boat para darle el método de glide . + testString: 'assert(typeof boat.glide === "function", "Your code should use the glideMixin on the boat object to give it the glide method.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let bird = { + name: "Donald", + numLegs: 2 +}; + +let boat = { + name: "Warrior", + type: "race-boat" +}; + +// Add your code below this line + + + + + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +let bird = { + name: "Donald", + numLegs: 2 +}; + +let boat = { + name: "Warrior", + type: "race-boat" +}; +function glideMixin (obj) { + obj.glide = () => 'Gliding!'; +} + +glideMixin(bird); +glideMixin(boat); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.spanish.md new file mode 100644 index 0000000000..c3c7a3e070 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-an-iife-to-create-a-module.spanish.md @@ -0,0 +1,81 @@ +--- +id: 587d7db2367417b2b2512b8c +title: Use an IIFE to Create a Module +localeTitle: Utilice un IIFE para crear un módulo +challengeType: 1 +--- + +## Description +
    +Una immediately invoked function expression ( IIFE ) se usa a menudo para agrupar la funcionalidad relacionada en un solo objeto o module . Por ejemplo, un desafío anterior definió dos mixins: +
    function glideMixin(obj) {
      obj.glide = function() {
        console.log("Gliding on the water");
      };
    }
    function flyMixin(obj) {
      obj.fly = function() {
        console.log("Flying, wooosh!");
      };
    }
    +Podemos agrupar estos mixins en un módulo de la siguiente manera: +
    let motionModule = (function () {
      return {
        glideMixin: function (obj) {
          obj.glide = function() {
            console.log("Gliding on the water");
          };
        },
        flyMixin: function(obj) {
          obj.fly = function() {
            console.log("Flying, wooosh!");
          };
        }
      }
    }) (); // The two parentheses cause the function to be immediately invoked
    +Tenga en cuenta que tiene una immediately invoked function expression ( IIFE ) que devuelve un objeto motionModule . Este objeto devuelto contiene todos los comportamientos de mixin como propiedades del objeto. +La ventaja del patrón del module es que todos los comportamientos de movimiento se pueden empaquetar en un solo objeto que luego pueden ser utilizados por otras partes de su código. Aquí hay un ejemplo usándolo: +
    motionModule.glideMixin(duck);
    duck.glide();
    +
    + +## Instructions +
    +Crea un module llamado funModule para envolver los dos mixins isCuteMixin y singMixin . funModule debería devolver un objeto. +
    + +## Tests +
    + +```yml +tests: + - text: funModule debe definirse y devolver un objeto. + testString: 'assert(typeof funModule === "object", "funModule should be defined and return an object.");' + - text: funModule.isCuteMixin debe acceder a una función. + testString: 'assert(typeof funModule.isCuteMixin === "function", "funModule.isCuteMixin should access a function.");' + - text: funModule.singMixin debe acceder a una función. + testString: 'assert(typeof funModule.singMixin === "function", "funModule.singMixin should access a function.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let isCuteMixin = function(obj) { + obj.isCute = function() { + return true; + }; +}; +let singMixin = function(obj) { + obj.sing = function() { + console.log("Singing to an awesome tune"); + }; +}; +``` + +
    + + + +
    + +## Solution +
    + + +```js +const funModule = (function () { + return { + isCuteMixin: obj => { + obj.isCute = () => true; + }, + singMixin: obj => { + obj.sing = () => console.log("Singing to an awesome tune"); + } + }; +})(); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.spanish.md new file mode 100644 index 0000000000..86b858c581 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-closure-to-protect-properties-within-an-object-from-being-modified-externally.spanish.md @@ -0,0 +1,69 @@ +--- +id: 587d7db2367417b2b2512b8a +title: Use Closure to Protect Properties Within an Object from Being Modified Externally +localeTitle: Utilice el cierre para proteger las propiedades dentro de un objeto de ser modificado externamente +challengeType: 1 +--- + +## Description +
    +En el desafío anterior, el bird tenía un name propiedad pública. Se considera público porque se puede acceder y cambiar fuera de la definición de bird . +
    bird.name = "Duffy";
    +Por lo tanto, cualquier parte de su código puede cambiar fácilmente el nombre de bird a cualquier valor. Piense en cosas como contraseñas y cuentas bancarias que se puedan cambiar fácilmente en cualquier parte de su base de código. Eso podría causar muchos problemas. +La forma más sencilla de hacer que las propiedades sean privadas es creando una variable dentro de la función constructora. Esto cambia el alcance de esa variable para que esté dentro de la función de constructor en lugar de estar disponible globalmente. De esta manera, a la propiedad solo se puede acceder y cambiar mediante métodos también dentro de la función de constructor. +
    function Bird() {
      let hatchedEgg = 10; // private property

      this.getHatchedEggCount = function() { // publicly available method that a bird object can use
        return hatchedEgg;
      };
    }
    let ducky = new Bird();
    ducky.getHatchedEggCount(); // returns 10
    +Aquí getHachedEggCount es un método privilegiado, porque tiene acceso a la variable privada hatchedEgg . Esto es posible porque hatchedEgg se declara en el mismo contexto que getHachedEggCount . En JavaScript, una función siempre tiene acceso al contexto en el que se creó. Esto se llama closure . +
    + +## Instructions +
    +Cambie cómo se declara el weight en la función Bird para que sea una variable privada. Luego, cree un método getWeight que devuelva el valor de weight . +
    + +## Tests +
    + +```yml +tests: + - text: La propiedad de weight debe ser una variable privada. + testString: 'assert(!code.match(/this\.weight/g), "The weight property should be a private variable.");' + - text: Su código debe crear un método en Bird llamado getWeight que devuelva el weight . + testString: 'assert((new Bird()).getWeight() === 15, "Your code should create a method in Bird called getWeight that returns the weight.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Bird() { + this.weight = 15; + + +} + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Bird() { + let weight = 15; + + this.getWeight = () => weight; +} +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.spanish.md new file mode 100644 index 0000000000..42b2ae6e8e --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-dot-notation-to-access-the-properties-of-an-object.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7dac367417b2b2512b74 +title: Use Dot Notation to Access the Properties of an Object +localeTitle: Usar la notación de puntos para acceder a las propiedades de un objeto +challengeType: 1 +--- + +## Description +
    +El último desafío creó un object con varias properties , ahora verá cómo acceder a los valores de esas properties . Aquí hay un ejemplo: +
    let duck = {
      name: "Aflac",
      numLegs: 2
    };
    console.log(duck.name);
    // This prints "Aflac" to the console
    +notación de puntos se utiliza en el nombre del object , duck , seguido del nombre de la property , name , para acceder al valor de "Aflac". +
    + +## Instructions +
    +Imprime las dos properties del objeto dog debajo de tu consola. +
    + +## Tests +
    + +```yml +tests: + - text: Debería usar console.log para imprimir el valor de la propiedad name del objeto dog . + testString: 'assert(/console.log\(.*dog\.name.*\)/g.test(code), "Your should use console.log to print the value for the name property of the dog object.");' + - text: Debería usar console.log para imprimir el valor de la propiedad numLegs del objeto dog . + testString: 'assert(/console.log\(.*dog\.numLegs.*\)/g.test(code), "Your should use console.log to print the value for the numLegs property of the dog object.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let dog = { + name: "Spot", + numLegs: 4 +}; +// Add your code below this line + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +let dog = { + name: "Spot", + numLegs: 4 +}; +console.log(dog.name); +console.log(dog.numLegs); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.spanish.md new file mode 100644 index 0000000000..7fb254212b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-inheritance-so-you-dont-repeat-yourself.spanish.md @@ -0,0 +1,113 @@ +--- +id: 587d7db0367417b2b2512b83 +title: Use Inheritance So You Don't Repeat Yourself +localeTitle: Usa la herencia para que no te repitas +challengeType: 1 +--- + +## Description +
    +Hay un principio en la programación llamado Don't Repeat Yourself (DRY) . La razón por la cual el código repetido es un problema es porque cualquier cambio requiere un código de corrección en varios lugares. Esto generalmente significa más trabajo para los programadores y más espacio para errores. +Observe en el siguiente ejemplo que Bird y Dog comparten el método de describe : +
    Bird.prototype = {
      constructor: Bird,
      describe: function() {
        console.log("My name is " + this.name);
      }
    };

    Dog.prototype = {
      constructor: Dog,
      describe: function() {
        console.log("My name is " + this.name);
      }
    };
    +El método describe se repite en dos lugares. El código se puede editar para seguir el principio DRY creando un supertype (o padre) llamado Animal : +
    function Animal() { };

    Animal.prototype = {
      constructor: Animal,
      describe: function() {
        console.log("My name is " + this.name);
      }
    };
    +Dado que Animal incluye el método de describe , puedes eliminarlo de Bird and Dog : +
    Bird.prototype = {
      constructor: Bird
    };

    Dog.prototype = {
      constructor: Dog
    };
    +
    + +## Instructions +
    +El método de eat se repite tanto en Cat como en Bear . Edite el código en el espíritu de DRY moviendo el método de eat al supertype Animal . +
    + +## Tests +
    + +```yml +tests: + - text: Animal.prototype debe tener la propiedad eat . + testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "Animal.prototype should have the eat property.");' + - text: Bear.prototype no debe tener la propiedad eat . + testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "Bear.prototype should not have the eat property.");' + - text: Cat.prototype no debe tener la propiedad eat . + testString: 'assert(!(Cat.prototype.hasOwnProperty("eat")), "Cat.prototype should not have the eat property.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Cat(name) { + this.name = name; +} + +Cat.prototype = { + constructor: Cat, + eat: function() { + console.log("nom nom nom"); + } +}; + +function Bear(name) { + this.name = name; +} + +Bear.prototype = { + constructor: Bear, + eat: function() { + console.log("nom nom nom"); + } +}; + +function Animal() { } + +Animal.prototype = { + constructor: Animal, + +}; +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Cat(name) { + this.name = name; +} + +Cat.prototype = { + constructor: Cat +}; + +function Bear(name) { + this.name = name; +} + +Bear.prototype = { + constructor: Bear +}; + +function Animal() { } + +Animal.prototype = { + constructor: Animal, + eat: function() { + console.log("nom nom nom"); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.spanish.md new file mode 100644 index 0000000000..a759bb629d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/use-prototype-properties-to-reduce-duplicate-code.spanish.md @@ -0,0 +1,75 @@ +--- +id: 587d7dae367417b2b2512b7c +title: Use Prototype Properties to Reduce Duplicate Code +localeTitle: Use las propiedades de prototipo para reducir el código duplicado +challengeType: 1 +--- + +## Description +
    +Dado que numLegs probablemente tendrá el mismo valor para todas las instancias de Bird , esencialmente tiene una variable duplicada numLegs dentro de cada instancia de Bird . +Esto puede no ser un problema cuando solo hay dos instancias, pero imagínese si hay millones de instancias. Eso sería un montón de variables duplicadas. +Una mejor manera es usar Bird's prototype Bird's . El prototype es un objeto que se comparte entre TODAS las instancias de Bird . Aquí se explica cómo agregar numLegs al Bird prototype : +
    Bird.prototype.numLegs = 2;
    +Ahora todas las instancias de Bird tienen la propiedad numLegs . +
    console.log(duck.numLegs); // prints 2
    console.log(canary.numLegs); // prints 2
    +Dado que todas las instancias tienen automáticamente las propiedades en el prototype , piense en un prototype como una "receta" para crear objetos. +Tenga en cuenta que el prototype para duck y canary es parte del constructor de Bird como Bird.prototype . Casi todos los objetos en JavaScript tienen una propiedad de prototype que forma parte de la función constructora que la creó. +
    + +## Instructions +
    +Agrega una propiedad numLegs al prototype de Dog +
    + +## Tests +
    + +```yml +tests: + - text: beagle debería tener una propiedad numLegs . + testString: 'assert(beagle.numLegs !== undefined, "beagle should have a numLegs property.");' + - text: beagle.numLegs debe ser un número. + testString: 'assert(typeof(beagle.numLegs) === "number" , "beagle.numLegs should be a number.");' + - text: numLegs debe ser una propiedad prototype y no una propiedad own . + testString: 'assert(beagle.hasOwnProperty("numLegs") === false, "numLegs should be a prototype property not an own property.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +function Dog(name) { + this.name = name; +} + + + +// Add your code above this line +let beagle = new Dog("Snoopy"); +``` + +
    + + + +
    + +## Solution +
    + + +```js +function Dog (name) { + this.name = name; +} +Dog.prototype.numLegs = 4; +let beagle = new Dog("Snoopy"); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.spanish.md new file mode 100644 index 0000000000..f0bb3fc741 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/object-oriented-programming/verify-an-objects-constructor-with-instanceof.spanish.md @@ -0,0 +1,71 @@ +--- +id: 587d7dae367417b2b2512b7a +title: Verify an Object's Constructor with instanceof +localeTitle: Verifique el constructor de un objeto con instanceof +challengeType: 1 +--- + +## Description +
    +Cada vez que una función constructora crea un nuevo objeto, se dice que ese objeto es una instance de su constructor. JavaScript ofrece una forma conveniente de verificar esto con el operador instanceof . instanceof permite comparar un objeto con un constructor, devolviendo true o false según si ese objeto fue creado con el constructor o no. Aquí hay un ejemplo: +
    let Bird = function(name, color) {
      this.name = name;
      this.color = color;
      this.numLegs = 2;
    }

    let crow = new Bird("Alexis", "black");

    crow instanceof Bird; // => true
    +Si un objeto se crea sin usar un constructor, instanceof verificará que no es una instancia de ese constructor: +
    let canary = {
      name: "Mildred",
      color: "Yellow",
      numLegs: 2
    };

    canary instanceof Bird; // => false
    +
    + +## Instructions +
    +Crear una nueva instancia del constructor de la House , llamándola myHouse y pasando varias habitaciones. Luego, use instanceof para verificar que es una instancia de House . +
    + +## Tests +
    + +```yml +tests: + - text: myHouse debería tener un atributo numBedrooms establecido en un número. + testString: 'assert(typeof myHouse.numBedrooms === "number", "myHouse should have a numBedrooms attribute set to a number.");' + - text: Asegúrese de verificar que myHouse es una instancia de House usa el operador instanceof . + testString: 'assert(/myHouse\s*instanceof\s*House/.test(code), "Be sure to verify that myHouse is an instance of House using the instanceof operator.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +/* jshint expr: true */ + +function House(numBedrooms) { + this.numBedrooms = numBedrooms; +} + +// Add your code below this line + + + +``` + +
    + + + +
    + +## Solution +
    + + +```js +function House(numBedrooms) { + this.numBedrooms = numBedrooms; +} +const myHouse = new House(4); +console.log(myHouse instanceof House); +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.spanish.md new file mode 100644 index 0000000000..839c05855b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/check-for-all-or-none.spanish.md @@ -0,0 +1,62 @@ +--- +id: 587d7dba367417b2b2512ba8 +title: Check for All or None +localeTitle: Comprobar por todos o ninguno +challengeType: 1 +--- + +## Description +
    +A veces, los patrones que desea buscar pueden tener partes que pueden o no existir. Sin embargo, puede ser importante verificarlos de todas formas. +Puede especificar la posible existencia de un elemento con un signo de interrogación, ? . Esto comprueba si hay cero o uno de los elementos anteriores. Puede pensar que este símbolo dice que el elemento anterior es opcional. +Por ejemplo, hay ligeras diferencias entre el inglés americano y el británico y puede usar el signo de interrogación para hacer coincidir ambas ortografías. +
    let american = "color";
    let british = "colour";
    let rainbowRegex= /colou?r/;
    rainbowRegex.test(american); // Returns true
    rainbowRegex.test(british); // Returns true
    +
    + +## Instructions +
    +Cambie el regex favRegex para que coincida con la versión del inglés americano (favorito) y del inglés británico (favorito) de la palabra. +
    + +## Tests +
    + +```yml +tests: + - text: 'Su expresión regular debe utilizar el símbolo opcional, ? . + testString: 'assert(favRegex.source.match(/\?/).length > 0, "Your regex should use the optional symbol, ?.");' + - text: Tu expresión regular debe coincidir con "favorite" + testString: 'assert(favRegex.test("favorite"), "Your regex should match "favorite"");' + - text: Tu expresión regular debe coincidir con "favourite" + testString: 'assert(favRegex.test("favourite"), "Your regex should match "favourite"");' + - text: Tu expresión regular no debe coincidir con "fav" + testString: 'assert(!favRegex.test("fav"), "Your regex should not match "fav"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let favWord = "favorite"; +let favRegex = /change/; // Change this line +let result = favRegex.test(favWord); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.spanish.md new file mode 100644 index 0000000000..c849846fbe --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/extract-matches.spanish.md @@ -0,0 +1,59 @@ +--- +id: 587d7db4367417b2b2512b92 +title: Extract Matches +localeTitle: Extraer fósforos +challengeType: 1 +--- + +## Description +
    +Hasta ahora, solo ha estado comprobando si existe un patrón o no dentro de una cadena. También puede extraer las coincidencias reales que encontró con el método .match() . +Para usar el método .match() , aplique el método en una cadena y pase la expresión regular dentro de los paréntesis. Aquí hay un ejemplo: +
    "Hello, World!".match(/Hello/);
    // Returns ["Hello"]
    let ourStr = "Regular expressions";
    let ourRegex = /expressions/;
    ourStr.match(ourRegex);
    // Returns ["expressions"]
    +
    + +## Instructions +
    +Aplique el método .match() para extraer la coding palabras. +
    + +## Tests +
    + +```yml +tests: + - text: El result debe tener la palabra coding + testString: 'assert(result.join() === "coding", "The result should have the word coding");' + - text: Tu regex codingRegex debería buscar la coding + testString: 'assert(codingRegex.source === "coding", "Your regex codingRegex should search for coding");' + - text: Deberías usar el método .match() . + testString: 'assert(code.match(/\.match\(.*\)/), "You should use the .match() method.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let extractStr = "Extract the word 'coding' from this string."; +let codingRegex = /change/; // Change this line +let result = extractStr; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.spanish.md new file mode 100644 index 0000000000..7d4ba6982c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching.spanish.md @@ -0,0 +1,56 @@ +--- +id: 587d7db6367417b2b2512b9b +title: Find Characters with Lazy Matching +localeTitle: Encuentra personajes con Lazy Matching +challengeType: 1 +--- + +## Description +
    +En expresiones regulares, una coincidencia greedy encuentra la parte más larga posible de una cadena que se ajusta al patrón de expresiones regulares y la devuelve como una coincidencia. La alternativa se denomina coincidencia lazy , que encuentra la parte más pequeña posible de la cadena que satisface el patrón de expresiones regulares. +Puede aplicar la expresión regular /t[az]*i/ a la cadena "titanic" . Esta expresión regular es básicamente un patrón que comienza con t , termina con i y tiene algunas letras en medio. +Las expresiones regulares son por defecto greedy , por lo que la coincidencia devolvería ["titani"] . Encuentra la subcadena más grande posible para ajustar el patrón. +Sin embargo, puedes usar el ? Personaje para cambiarlo a juego lazy . "titanic" emparejado contra la expresión regular ajustada de /t[az]*?i/ devuelve ["ti"] . +
    + +## Instructions +
    +/<.*>/ la expresión regular /<.*>/ para devolver la etiqueta HTML <h1> y no el texto "<h1>Winter is coming</h1>" . Recuerda el comodín . En una expresión regular coincide con cualquier carácter. +
    + +## Tests +
    + +```yml +tests: + - text: La variable de result debe ser una matriz con <h1> en ella + testString: 'assert(result[0] == "

    ", "The result variable should be an array with <h1> in it");' + +``` + +

    + +## Challenge Seed +
    + +
    + +```js +let text = "

    Winter is coming

    "; +let myRegex = /<.*>/; // Change this line +let result = text.match(myRegex); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.spanish.md new file mode 100644 index 0000000000..8a60db52b0 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-more-than-the-first-match.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7db4367417b2b2512b93 +title: Find More Than the First Match +localeTitle: Encuentra más que el primer partido +challengeType: 1 +--- + +## Description +
    +Hasta ahora, solo ha podido extraer o buscar un patrón una vez. +
    let testStr = "Repeat, Repeat, Repeat";
    let ourRegex = /Repeat/;
    testStr.match(ourRegex);
    // Returns ["Repeat"]
    +Para buscar o extraer un patrón más de una vez, puede usar la bandera g . +
    let repeatRegex = /Repeat/g;
    testStr.match(repeatRegex);
    // Returns ["Repeat", "Repeat", "Repeat"]
    +
    + +## Instructions +
    +Usando el regex starRegex , encuentra y extrae ambas palabras "Twinkle" de la cadena twinkleStar . +Nota
    Puedes tener múltiples banderas en tu expresión regular como /search/gi +
    + +## Tests +
    + +```yml +tests: + - text: Tu regex starRegex debe usar la bandera global g + testString: 'assert(starRegex.flags.match(/g/).length == 1, "Your regex starRegex should use the global flag g");' + - text: Su regex starRegex debe usar el indicador de mayúsculas y minúsculas i + testString: 'assert(starRegex.flags.match(/i/).length == 1, "Your regex starRegex should use the case insensitive flag i");' + - text: Tu coincidencia debe coincidir con ambas apariciones de la palabra "Twinkle" + testString: 'assert(result.sort().join() == twinkleStar.match(/twinkle/gi).sort().join(), "Your match should match both occurrences of the word "Twinkle"");' + - text: El result tu partida debe tener dos elementos. + testString: 'assert(result.length == 2, "Your match result should have two elements in it.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let twinkleStar = "Twinkle, twinkle, little star"; +let starRegex = /change/; // Change this line +let result = twinkleStar; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.spanish.md new file mode 100644 index 0000000000..65386dd17a --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/find-one-or-more-criminals-in-a-hunt.spanish.md @@ -0,0 +1,74 @@ +--- +id: 587d7db7367417b2b2512b9c +title: Find One or More Criminals in a Hunt +localeTitle: Encuentra uno o más criminales en una cacería +challengeType: 1 +--- + +## Description +
    +Tiempo para pausar y probar sus nuevas habilidades de escritura de expresiones regulares. Un grupo de criminales escapó de la cárcel y se escapó, pero no sabes cuántos. Sin embargo, sí sabes que permanecen juntos cuando están cerca de otras personas. Eres responsable de encontrar a todos los criminales a la vez. +Aquí hay un ejemplo para revisar cómo hacer esto: +La expresión regular /z+/ coincide con la letra z cuando aparece una o más veces seguidas. Encontraría coincidencias en todas las cadenas siguientes: +
    "z"
    "zzzzzz"
    "ABCzzzz"
    "zzzzABC"
    "abczzzzzzzzzzzzzzzzzzzzzabc"
    +Pero no encuentra coincidencias en las siguientes cadenas ya que no hay caracteres de la letra z : +
    ""
    "ABC"
    "abcabc"
    +
    + +## Instructions +
    +Escriba una expresión regular greedy que encuentre uno o más delincuentes dentro de un grupo de otras personas. Un criminal está representado por la letra mayúscula C +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe coincidir con one criminal (" C ") en "C" + testString: 'assert("C".match(reCriminals) && "C".match(reCriminals)[0] == "C", "Your regex should match one criminal ("C") in "C"");' + - text: Su expresión regular debe coincidir con two delincuentes (" CC ") en "CC" + testString: 'assert("CC".match(reCriminals) && "CC".match(reCriminals)[0] == "CC", "Your regex should match two criminals ("CC") in "CC"");' + - text: Su expresión regular debe coincidir con three delincuentes (" CCC ") en "P1P5P4CCCP2P6P3" + testString: 'assert("P1P5P4CCCP2P6P3".match(reCriminals) && "P1P5P4CCCP2P6P3".match(reCriminals)[0] == "CCC", "Your regex should match three criminals ("CCC") in "P1P5P4CCCP2P6P3"");' + - text: Su expresión regular debe coincidir con five delincuentes (" CCCCC ") en "P6P2P7P4P5CCCCCP3P1" + testString: 'assert("P6P2P7P4P5CCCCCP3P1".match(reCriminals) && "P6P2P7P4P5CCCCCP3P1".match(reCriminals)[0] == "CCCCC", "Your regex should match five criminals ("CCCCC") in "P6P2P7P4P5CCCCCP3P1"");' + - text: Tu expresión regular no debe coincidir con ningún criminal en "" + testString: 'assert(!reCriminals.test(""), "Your regex should not match any criminals in """);' + - text: Su expresión regular no debe coincidir con ningún criminal en "P1P2P3" + testString: 'assert(!reCriminals.test("P1P2P3"), "Your regex should not match any criminals in "P1P2P3"");' + - text: Su expresión regular debe coincidir con fifty delincuentes (" CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ") en "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3" . + testString: 'assert("P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3".match(reCriminals) && "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3".match(reCriminals)[0] == "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", "Your regex should match fifty criminals ("CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC") in "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +// example crowd gathering +let crowd = 'P1P2P3P4P5P6CCCP7P8P9'; + +let reCriminals = /./; // Change this line + +let matchedCriminals = crowd.match(reCriminals); +console.log(matchedCriminals); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.spanish.md new file mode 100644 index 0000000000..57b4e6076d --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/ignore-case-while-matching.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7db4367417b2b2512b91 +title: Ignore Case While Matching +localeTitle: Ignorar caso mientras coinciden +challengeType: 1 +--- + +## Description +
    +Hasta ahora, has visto expresiones regulares para hacer coincidencias literales de cadenas. Pero a veces, es posible que también desee igualar las diferencias de casos. +Caso (o, a veces, mayúsculas) es la diferencia entre letras mayúsculas y minúsculas. Ejemplos de mayúsculas son "A" , "B" y "C" . Ejemplos de minúsculas son "a" , "b" y "c" . +Puedes hacer coincidir ambos casos usando lo que se llama una bandera. Hay otras banderas, pero aquí se enfocará en la bandera que ignora el caso, la bandera i . Puedes usarlo añadiéndolo a la expresión regular. Un ejemplo de uso de esta bandera es /ignorecase/i . Esta expresión regular puede coincidir con las cadenas "ignorecase" , "igNoreCase" e "IgnoreCase" . +
    + +## Instructions +
    +Escriba una expresión regular fccRegex para que coincida con "freeCodeCamp" , sin importar su caso. Su expresión regular no debe coincidir con ninguna abreviatura o variación con espacios. +
    + +## Tests +
    + +```yml +tests: + - text: Tu expresión regular debe coincidir con freeCodeCamp + testString: 'assert(fccRegex.test("freeCodeCamp"), "Your regex should match freeCodeCamp");' + - text: Tu expresión regular debe coincidir con FreeCodeCamp + testString: 'assert(fccRegex.test("FreeCodeCamp"), "Your regex should match FreeCodeCamp");' + - text: Tu expresión regular debe coincidir con FreecodeCamp + testString: 'assert(fccRegex.test("FreecodeCamp"), "Your regex should match FreecodeCamp");' + - text: Tu expresión regular debe coincidir con FreeCodecamp + testString: 'assert(fccRegex.test("FreeCodecamp"), "Your regex should match FreeCodecamp");' + - text: Su expresión regular no debe coincidir con Free Code Camp + testString: 'assert(!fccRegex.test("Free Code Camp"), "Your regex should not match Free Code Camp");' + - text: Tu expresión regular debe coincidir con FreeCOdeCamp + testString: 'assert(fccRegex.test("FreeCOdeCamp"), "Your regex should match FreeCOdeCamp");' + - text: Su expresión regular no debe coincidir con FCC + testString: 'assert(!fccRegex.test("FCC"), "Your regex should not match FCC");' + - text: Tu expresión regular debe coincidir con FrEeCoDeCamp + testString: 'assert(fccRegex.test("FrEeCoDeCamp"), "Your regex should match FrEeCoDeCamp");' + - text: Tu expresión regular debe coincidir con FrEeCodECamp + testString: 'assert(fccRegex.test("FrEeCodECamp"), "Your regex should match FrEeCodECamp");' + - text: Tu expresión regular debe coincidir con FReeCodeCAmp + testString: 'assert(fccRegex.test("FReeCodeCAmp"), "Your regex should match FReeCodeCAmp");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let myString = "freeCodeCamp"; +let fccRegex = /change/; // Change this line +let result = fccRegex.test(myString); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.spanish.md new file mode 100644 index 0000000000..2c42580d83 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-a-literal-string-with-different-possibilities.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7db4367417b2b2512b90 +title: Match a Literal String with Different Possibilities +localeTitle: Unir una cadena literal con diferentes posibilidades +challengeType: 1 +--- + +## Description +
    +Usando expresiones regulares como /coding/ , puede buscar el patrón "coding" en otra cadena. +Esto es poderoso para buscar cadenas simples, pero está limitado a un solo patrón. Puede buscar múltiples patrones utilizando la alternation u operador OR : | . +Este operador hace coincidir los patrones antes o después de él. Por ejemplo, si desea hacer coincidir "yes" o "no" , la expresión regular que desea es /yes|no/ . +También puede buscar más de dos patrones. Puede hacer esto agregando más patrones con más operadores OR que los separan, como /yes|no|maybe/ . +
    + +## Instructions +
    +Complete el regex petRegex para que coincida con las mascotas "dog" , "cat" , "bird" o "fish" . +
    + +## Tests +
    + +```yml +tests: + - text: Su regex petRegex debe devolver true para la cadena "John has a pet dog." + testString: 'assert(petRegex.test("John has a pet dog."), "Your regex petRegex should return true for the string "John has a pet dog."");' + - text: Su regex petRegex debe devolver false para la cadena "Emma has a pet rock." + testString: 'assert(!petRegex.test("Emma has a pet rock."), "Your regex petRegex should return false for the string "Emma has a pet rock."");' + - text: Tu regex petRegex debe devolver true para la cadena "Emma has a pet bird." + testString: 'assert(petRegex.test("Emma has a pet bird."), "Your regex petRegex should return true for the string "Emma has a pet bird."");' + - text: Tu regex petRegex debe devolver true para la cadena "Liz has a pet cat." + testString: 'assert(petRegex.test("Liz has a pet cat."), "Your regex petRegex should return true for the string "Liz has a pet cat."");' + - text: Su regex petRegex debe devolver false para la cadena "Kara has a pet dolphin." + testString: 'assert(!petRegex.test("Kara has a pet dolphin."), "Your regex petRegex should return false for the string "Kara has a pet dolphin."");' + - text: Su regex petRegex debe devolver true para la cadena "Alice has a pet fish." + testString: 'assert(petRegex.test("Alice has a pet fish."), "Your regex petRegex should return true for the string "Alice has a pet fish."");' + - text: Su regex petRegex debe devolver false para la cadena "Jimmy has a pet computer." + testString: 'assert(!petRegex.test("Jimmy has a pet computer."), "Your regex petRegex should return false for the string "Jimmy has a pet computer."");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let petString = "James has a pet cat."; +let petRegex = /change/; // Change this line +let result = petRegex.test(petString); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.spanish.md new file mode 100644 index 0000000000..7b3ea38bd0 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-letters-and-numbers.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d7db7367417b2b2512b9f +title: Match All Letters and Numbers +localeTitle: Unir todas las letras y números +challengeType: 1 +--- + +## Description +
    +Al usar clases de caracteres, pudo buscar todas las letras del alfabeto con [az] . Este tipo de clase de caracteres es lo suficientemente común como para que haya un atajo, aunque también incluye algunos caracteres adicionales. +La clase de caracteres más cercana en JavaScript para que coincida con el alfabeto es \w . Este atajo es igual a [A-Za-z0-9_] . Esta clase de caracteres coincide con mayúsculas y minúsculas más números. Tenga en cuenta que esta clase de caracteres también incluye el carácter de subrayado ( _ ). +
    let longHand = /[A-Za-z0-9_]+/;
    let shortHand = /\w+/;
    let numbers = "42";
    let varNames = "important_var";
    longHand.test(numbers); // Returns true
    shortHand.test(numbers); // Returns true
    longHand.test(varNames); // Returns true
    shortHand.test(varNames); // Returns true
    +Estas clases de caracteres de acceso directo también se conocen como shorthand character classes . +
    + +## Instructions +
    +Use la clase de caracteres abreviados \w para contar el número de caracteres alfanuméricos en varias comillas y cadenas. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(alphabetRegexV2.global, "Your regex should use the global flag.");' + - text: Tu expresión regular debe usar el carácter abreviado + testString: 'assert(/\\w/.test(alphabetRegexV2.source), "Your regex should use the shorthand character \w to match all characters which are alphanumeric.");' + - text: Su expresión regular debe encontrar 31 caracteres alfanuméricos en "Los cinco magos de boxeo saltan rápidamente". + testString: 'assert("The five boxing wizards jump quickly.".match(alphabetRegexV2).length === 31, "Your regex should find 31 alphanumeric characters in "The five boxing wizards jump quickly."");' + - text: Su expresión regular debe encontrar 32 caracteres alfanuméricos en "Empaque mi caja con cinco docenas de jarras de licor". + testString: 'assert("Pack my box with five dozen liquor jugs.".match(alphabetRegexV2).length === 32, "Your regex should find 32 alphanumeric characters in "Pack my box with five dozen liquor jugs."");' + - text: Tu expresión regular debe encontrar 30 caracteres alfanuméricos en "¡Cómo saltan las cebras!" + testString: 'assert("How vexingly quick daft zebras jump!".match(alphabetRegexV2).length === 30, "Your regex should find 30 alphanumeric characters in "How vexingly quick daft zebras jump!"");' + - text: Su expresión regular debe encontrar 36 caracteres alfanuméricos en "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ." + testString: 'assert("123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.".match(alphabetRegexV2).length === 36, "Your regex should find 36 alphanumeric characters in "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "The five boxing wizards jump quickly."; +let alphabetRegexV2 = /change/; // Change this line +let result = quoteSample.match(alphabetRegexV2).length; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.spanish.md new file mode 100644 index 0000000000..5cd2835b67 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-non-numbers.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7db8367417b2b2512ba1 +title: Match All Non-Numbers +localeTitle: Coincidir con todos los no números +challengeType: 1 +--- + +## Description +
    +El último desafío mostró cómo buscar dígitos usando el método abreviado \d con una minúscula d . También puede buscar no dígitos usando un atajo similar que use una D mayúscula en su lugar. +El atajo para buscar caracteres sin dígitos es \D Esto es igual a la clase de caracteres [^0-9] , que busca un solo carácter que no sea un número entre cero y nueve. +
    + +## Instructions +
    +Use la clase de caracteres abreviados para no dígitos \D para contar cuántos no dígitos hay en los títulos de las películas. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe usar el carácter de acceso directo para hacer coincidir los caracteres que no son dígitos + testString: 'assert(/\\D/.test(noNumRegex.source), "Your regex should use the shortcut character to match non-digit characters");' + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(noNumRegex.global, "Your regex should use the global flag.");' + - text: Su expresión regular no debe encontrar dígitos que no sean dígitos en "9" . + testString: 'assert("9".match(noNumRegex) == null, "Your regex should find no non-digits in "9".");' + - text: Su expresión regular debe encontrar 6 no dígitos en "Catch 22" . + testString: 'assert("Catch 22".match(noNumRegex).length == 6, "Your regex should find 6 non-digits in "Catch 22".");' + - text: Su expresión regular debe encontrar 11 no dígitos en "101 Dalmatians" . + testString: 'assert("101 Dalmatians".match(noNumRegex).length == 11, "Your regex should find 11 non-digits in "101 Dalmatians".");' + - text: 'Su expresión regular debe encontrar 15 no dígitos en "Uno, dos, tres" .' + testString: 'assert("One, Two, Three".match(noNumRegex).length == 15, "Your regex should find 15 non-digits in "One, Two, Three".");' + - text: Su expresión regular debe encontrar 12 no dígitos en "21 Jump Street" . + testString: 'assert("21 Jump Street".match(noNumRegex).length == 12, "Your regex should find 12 non-digits in "21 Jump Street".");' + - text: "Su expresión regular debe encontrar 17 dígitos que no sean dígitos en " 2001: A Space Odyssey ". ' + testString: 'assert("2001: A Space Odyssey".match(noNumRegex).length == 17, "Your regex should find 17 non-digits in "2001: A Space Odyssey".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let numString = "Your sandwich will be $5.00"; +let noNumRegex = /change/; // Change this line +let result = numString.match(noNumRegex).length; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.spanish.md new file mode 100644 index 0000000000..5699f151a8 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-all-numbers.spanish.md @@ -0,0 +1,68 @@ +--- +id: 5d712346c441eddfaeb5bdef +title: Match All Numbers +localeTitle: Coincidir todos los números +challengeType: 1 +--- + +## Description +
    +Ha aprendido atajos para patrones de cadena comunes como alfanuméricos. Otro patrón común es buscar solo dígitos o números. +El atajo para buscar caracteres de dígitos es \d , con una minúscula d . Esto es igual a la clase de caracteres [0-9] , que busca un solo carácter de cualquier número entre cero y nueve. +
    + +## Instructions +
    +Use la clase de caracteres abreviados \d para contar cuántos dígitos hay en los títulos de las películas. Los números escritos ("seis" en lugar de 6) no cuentan. +
    + +## Tests +
    + +```yml +tests: + - text: Tu expresión regular debe usar el atajo para coincidir con los dígitos. + testString: 'assert(/\\d/.test(numRegex.source), "Your regex should use the shortcut character to match digit characters");' + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(numRegex.global, "Your regex should use the global flag.");' + - text: Su expresión regular debe encontrar 1 dígito en "9" . + testString: 'assert("9".match(numRegex).length == 1, "Your regex should find 1 digit in "9".");' + - text: Su expresión regular debe encontrar 2 dígitos en "Catch 22" . + testString: 'assert("Catch 22".match(numRegex).length == 2, "Your regex should find 2 digits in "Catch 22".");' + - text: Su expresión regular debe encontrar 3 dígitos en "101 Dalmatians" . + testString: 'assert("101 Dalmatians".match(numRegex).length == 3, "Your regex should find 3 digits in "101 Dalmatians".");' + - text: 'Su expresión regular no debe encontrar dígitos en "One, Two, Three" .' + testString: 'assert("One, Two, Three".match(numRegex) == null, "Your regex should find no digits in "One, Two, Three".");' + - text: Su expresión regular debe encontrar 2 dígitos en "21 Jump Street" . + testString: 'assert("21 Jump Street".match(numRegex).length == 2, "Your regex should find 2 digits in "21 Jump Street".");' + - text: 'Su expresión regular debe encontrar 4 dígitos en "2001: A Space Odyssey" .' + testString: 'assert("2001: A Space Odyssey".match(numRegex).length == 4, "Your regex should find 4 digits in "2001: A Space Odyssey".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let numString = "Your sandwich will be $5.00"; +let numRegex = /change/; // Change this line +let result = numString.match(numRegex).length; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.spanish.md new file mode 100644 index 0000000000..6b4a240d19 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-anything-with-wildcard-period.spanish.md @@ -0,0 +1,73 @@ +--- +id: 587d7db5367417b2b2512b94 +title: Match Anything with Wildcard Period +localeTitle: Coincidir cualquier cosa con el período de comodín +challengeType: 1 +--- + +## Description +
    +A veces no (o no es necesario) conocer los caracteres exactos en sus patrones. Pensar en todas las palabras que coinciden, por ejemplo, una falta de ortografía llevaría mucho tiempo. Por suerte, se puede ahorrar tiempo utilizando el carácter comodín: . +El carácter comodín . coincidirá con cualquier personaje. El comodín es también llamado dot y period . Puede usar el carácter comodín como cualquier otro carácter en la expresión regular. Por ejemplo, si desea hacer coincidir "hug" , "huh" , "hut" y "hum" , puede usar la expresión regular /hu./ para hacer coincidir las cuatro palabras. +
    let humStr = "I'll hum a song";
    let hugStr = "Bear hug";
    let huRegex = /hu./;
    humStr.match(huRegex); // Returns ["hum"]
    hugStr.match(huRegex); // Returns ["hug"]
    +
    + +## Instructions +
    +Complete la expresión regular unRegex para que coincida con las cadenas "run" , "sun" , "fun" , "pun" , "nun" y "bun" . Su expresión regular debe utilizar el carácter comodín. +
    + +## Tests +
    + +```yml +tests: + - text: Deberías usar el método .test() . + testString: 'assert(code.match(/\.test\(.*\)/), "You should use the .test() method.");' + - text: Debe utilizar el carácter comodín en su expresión regular unRegex + testString: 'assert(/\./.test(unRegex.source), "You should use the wildcard character in your regex unRegex");' + - text: Su expresión regular unRegex debe coincidir con "run" en "Let us go on a run." + testString: 'assert(unRegex.test("Let us go on a run."), "Your regex unRegex should match "run" in "Let us go on a run."");' + - text: Su expresión regular unRegex debe coincidir con "sun" en "The sun is out today." + testString: 'assert(unRegex.test("The sun is out today."), "Your regex unRegex should match "sun" in "The sun is out today."");' + - text: Su expresión regular unRegex debe coincidir con "fun" en "Coding is a lot of fun." + testString: 'assert(unRegex.test("Coding is a lot of fun."), "Your regex unRegex should match "fun" in "Coding is a lot of fun."");' + - text: Su expresión regular unRegex debe coincidir con "pun" en "Seven days without a pun makes one weak." + testString: 'assert(unRegex.test("Seven days without a pun makes one weak."), "Your regex unRegex should match "pun" in "Seven days without a pun makes one weak."");' + - text: Tu expresión regular unRegex debe coincidir con "nun" en "One takes a vow to be a nun." + testString: 'assert(unRegex.test("One takes a vow to be a nun."), "Your regex unRegex should match "nun" in "One takes a vow to be a nun."");' + - text: Tu regex unRegex debe coincidir con "bun" en "She got fired from the hot dog stand for putting her hair in a bun." + testString: 'assert(unRegex.test("She got fired from the hot dog stand for putting her hair in a bun."), "Your regex unRegex should match "bun" in "She got fired from the hot dog stand for putting her hair in a bun."");' + - text: Su expresión regular unRegex no debe coincidir con "There is a bug in my code." + testString: 'assert(!unRegex.test("There is a bug in my code."), "Your regex unRegex should not match "There is a bug in my code."");' + - text: Tu expresión regular unRegex no debe coincidir con "Catch me if you can." + testString: 'assert(!unRegex.test("Can me if you can."), "Your regex unRegex should not match "Catch me if you can."");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let exampleStr = "Let's have fun with regular expressions!"; +let unRegex = /change/; // Change this line +let result = unRegex.test(exampleStr); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.spanish.md new file mode 100644 index 0000000000..cc1e5217e9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-beginning-string-patterns.spanish.md @@ -0,0 +1,61 @@ +--- +id: 587d7db7367417b2b2512b9d +title: Match Beginning String Patterns +localeTitle: Emparejar patrones de cuerdas que comienzan +challengeType: 1 +--- + +## Description +
    +Los desafíos anteriores mostraron que las expresiones regulares se pueden usar para buscar una serie de coincidencias. También se utilizan para buscar patrones en posiciones específicas en cadenas. +En un desafío anterior, caret carácter de caret ( ^ ) dentro de un character set para crear un negated character set en la forma [^thingsThatWillNotBeMatched] . Fuera de un character set , el caret se utiliza para buscar patrones al principio de las cadenas. +
    let firstString = "Ricky is first and can be found.";
    let firstRegex = /^Ricky/;
    firstRegex.test(firstString);
    // Returns true
    let notFirst = "You can't find Ricky now.";
    firstRegex.test(notFirst);
    // Returns false
    +
    + +## Instructions +
    +Use el carácter de caret en una expresión regular para encontrar "Cal" solo al principio de la cadena rickyAndCal . +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe buscar "Cal" con una letra mayúscula. + testString: 'assert(calRegex.source == "^Cal", "Your regex should search for "Cal" with a capital letter.");' + - text: Su expresión regular no debe usar ninguna bandera. + testString: 'assert(calRegex.flags == "", "Your regex should not use any flags.");' + - text: Tu expresión regular debe coincidir con "Cal" al principio de la cadena. + testString: 'assert(calRegex.test("Cal and Ricky both like racing."), "Your regex should match "Cal" at the beginning of the string.");' + - text: Su expresión regular no debe coincidir con "Cal" en medio de una cadena. + testString: 'assert(!calRegex.test("Ricky and Cal both like racing."), "Your regex should not match "Cal" in the middle of a string.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let rickyAndCal = "Cal and Ricky both like racing."; +let calRegex = /change/; // Change this line +let result = calRegex.test(rickyAndCal); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.spanish.md new file mode 100644 index 0000000000..8347ed0508 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-one-or-more-times.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d7db6367417b2b2512b99 +title: Match Characters that Occur One or More Times +localeTitle: Relacionar los caracteres que ocurren una o más veces +challengeType: 1 +--- + +## Description +
    +A veces, debe hacer coincidir un carácter (o grupo de caracteres) que aparece una o más veces seguidas. Esto significa que ocurre al menos una vez, y puede repetirse. +Puede utilizar el carácter + para comprobar si ese es el caso. Recuerda, el personaje o patrón tiene que estar presente consecutivamente. Es decir, el personaje tiene que repetir uno tras otro. +Por ejemplo, /a+/g encontraría una coincidencia en "abc" y devolvería ["a"] . Debido al + , también encontraría una única coincidencia en "aabc" y devolvería ["aa"] . +Si se comprueba en lugar de la cadena "abab" , sería encontrar dos partidos y volver ["a", "a"] , porque los a caracteres que no están en una fila - no es un b entre ellos. Finalmente, dado que no hay "a" a "a" en la cadena "bcd" , no encontrará una coincidencia. +
    + +## Instructions +
    +Desea encontrar coincidencias cuando la letra s aparece una o más veces en "Mississippi" . Escribe una expresión regular que use el signo + . +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular myRegex debe utilizar el + signo para que coincida con uno o más s caracteres. + testString: 'assert(/\+/.test(myRegex.source), "Your regex myRegex should use the + sign to match one or more s characters.");' + - text: Tu regex myRegex debe coincidir con 2 elementos. + testString: 'assert(result.length == 2, "Your regex myRegex should match 2 items.");' + - text: La variable de result debe ser una matriz con dos coincidencias de "ss" + testString: 'assert(result[0] == "ss" && result[1] == "ss", "The result variable should be an array with two matches of "ss"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let difficultSpelling = "Mississippi"; +let myRegex = /change/; // Change this line +let result = difficultSpelling.match(myRegex); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.spanish.md new file mode 100644 index 0000000000..943d2d9929 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-characters-that-occur-zero-or-more-times.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7db6367417b2b2512b9a +title: Match Characters that Occur Zero or More Times +localeTitle: Caracteres de coincidencia que ocurren cero o más veces +challengeType: 1 +--- + +## Description +
    +El último desafío usó el signo más + para buscar caracteres que aparecen una o más veces. También hay una opción que coincide con los caracteres que aparecen cero o más veces. +El personaje para hacer esto es el asterisk o star : * . +
    let soccerWord = "gooooooooal!";
    let gPhrase = "gut feeling";
    let oPhrase = "over the moon";
    let goRegex = /go*/;
    soccerWord.match(goRegex); // Returns ["goooooooo"]
    gPhrase.match(goRegex); // Returns ["g"]
    oPhrase.match(goRegex); // Returns null
    +
    + +## Instructions +
    +Cree un regex chewieRegex que use el carácter * para que coincida con todos los caracteres "a" superiores e inferiores en chewieQuote . Su expresión regular no necesita indicadores y no debe coincidir con ninguna de las otras comillas. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular chewieRegex debe utilizar el * carácter a cero o más a personajes. + testString: 'assert(/\*/.test(chewieRegex.source), "Your regex chewieRegex should use the * character to match zero or more a characters.");' + - text: Tu regex chewieRegex debe coincidir con 16 caracteres. + testString: 'assert(result[0].length === 16, "Your regex chewieRegex should match 16 characters.");' + - text: Tu expresión regular debe coincidir con "Aaaaaaaaaaaaaaaa" . + testString: 'assert(result[0] === "Aaaaaaaaaaaaaaaa", "Your regex should match "Aaaaaaaaaaaaaaaa".");' + - text: 'Tu expresión regular no debe coincidir con ningún carácter en "He made a fair move. Screaming about it can't help you." ' + testString: 'assert(!"He made a fair move. Screaming about it can\"t help you.".match(chewieRegex), "Your regex should not match any characters in "He made a fair move. Screaming about it can't help you."");' + - text: "Tu expresión regular no debe coincidir con ningún carácter en "Let him have it. It's not wise to upset a Wookiee." ' + testString: 'assert(!"Let him have it. It\"s not wise to upset a Wookiee.".match(chewieRegex), "Your regex should not match any characters in "Let him have it. It's not wise to upset a Wookiee."");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let chewieQuote = "Aaaaaaaaaaaaaaaarrrgh!"; +let chewieRegex = /change/; // Change this line +let result = chewieQuote.match(chewieRegex); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.spanish.md new file mode 100644 index 0000000000..790f2e6c4b --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns.spanish.md @@ -0,0 +1,59 @@ +--- +id: 587d7db7367417b2b2512b9e +title: Match Ending String Patterns +localeTitle: Coincidir con patrones de cadena +challengeType: 1 +--- + +## Description +
    +En el último desafío, aprendiste a usar el carácter de caret para buscar patrones al principio de las cadenas. También hay una forma de buscar patrones al final de las cadenas. +Puede buscar el final de las cadenas con el dollar sign $ al final de la expresión regular. +
    let theEnding = "This is a never ending story";
    let storyRegex = /story$/;
    storyRegex.test(theEnding);
    // Returns true
    let noEnding = "Sometimes a story will have to end";
    storyRegex.test(noEnding);
    // Returns false
    +
    + +## Instructions +
    +Use el carácter de ancla ( $ ) para que coincida con la cadena "caboose" al final de la cadena caboose . +
    + +## Tests +
    + +```yml +tests: + - text: Debe buscar "caboose" con el signo de dólar $ ancla en su expresión regular. + testString: 'assert(lastRegex.source == "caboose$", "You should search for "caboose" with the dollar sign $ anchor in your regex.");' + - text: Su expresión regular no debe usar ninguna bandera. + testString: 'assert(lastRegex.flags == "", "Your regex should not use any flags.");' + - text: Debe coincidir con "caboose" al final de la cadena "The last car on a train is the caboose" + testString: 'assert(lastRegex.test("The last car on a train is the caboose"), "You should match "caboose" at the end of the string "The last car on a train is the caboose"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let caboose = "The last car on a train is the caboose"; +let lastRegex = /change/; // Change this line +let result = lastRegex.test(caboose); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.spanish.md new file mode 100644 index 0000000000..21478f76b9 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-everything-but-letters-and-numbers.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7db8367417b2b2512ba0 +title: Match Everything But Letters and Numbers +localeTitle: Unir todo, excepto letras y números +challengeType: 1 +--- + +## Description +
    +Ha aprendido que puede usar un atajo para hacer coincidir los caracteres alfanuméricos [A-Za-z0-9_] usando \w . Un patrón natural que quizás desee buscar es el opuesto a los alfanuméricos. +Puede buscar lo contrario de \w con \W Tenga en cuenta, el patrón opuesto utiliza una letra mayúscula. Este atajo es el mismo que [^A-Za-z0-9_] . +
    let shortHand = /\W/;
    let numbers = "42%";
    let sentence = "Coding!";
    numbers.match(shortHand); // Returns ["%"]
    sentence.match(shortHand); // Returns ["!"]
    +
    + +## Instructions +
    +Use la clase de caracteres abreviados \W para contar el número de caracteres no alfanuméricos en varias comillas y cadenas. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(nonAlphabetRegex.global, "Your regex should use the global flag.");' + - text: Su expresión regular debe encontrar 6 caracteres no alfanuméricos en "Los cinco asistentes de boxeo saltan rápidamente". + testString: 'assert("The five boxing wizards jump quickly.".match(nonAlphabetRegex).length == 6, "Your regex should find 6 non-alphanumeric characters in "The five boxing wizards jump quickly.".");' + - text: Tu expresión regular debe usar el carácter de taquigrafía. + testString: 'assert(/\\W/.test(nonAlphabetRegex.source), "Your regex should use the shorthand character to match characters which are non-alphanumeric.");' + - text: Su expresión regular debe encontrar 8 caracteres no alfanuméricos en "Empaque mi caja con cinco docenas de jarras de licor". + testString: 'assert("Pack my box with five dozen liquor jugs.".match(nonAlphabetRegex).length == 8, "Your regex should find 8 non-alphanumeric characters in "Pack my box with five dozen liquor jugs."");' + - text: Tu expresión regular debe encontrar 6 caracteres no alfanuméricos en "¡Qué rápido y zumbido de zebras!" + testString: 'assert("How vexingly quick daft zebras jump!".match(nonAlphabetRegex).length == 6, "Your regex should find 6 non-alphanumeric characters in "How vexingly quick daft zebras jump!"");' + - text: Su expresión regular debe encontrar 12 caracteres no alfanuméricos en "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ." + testString: 'assert("123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ.".match(nonAlphabetRegex).length == 12, "Your regex should find 12 non-alphanumeric characters in "123 456 7890 ABC def GHI jkl MNO pqr STU vwx YZ."");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "The five boxing wizards jump quickly."; +let nonAlphabetRegex = /change/; // Change this line +let result = quoteSample.match(nonAlphabetRegex).length; +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.spanish.md new file mode 100644 index 0000000000..574c8d4539 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-letters-of-the-alphabet.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d7db5367417b2b2512b96 +title: Match Letters of the Alphabet +localeTitle: Combina las letras del alfabeto +challengeType: 1 +--- + +## Description +
    +Vio cómo puede usar los character sets para especificar un grupo de caracteres para hacer coincidir, pero eso es mucho para escribir cuando necesita hacer coincidir una gran variedad de caracteres (por ejemplo, todas las letras del alfabeto). Afortunadamente, hay una característica incorporada que hace que esto sea breve y simple. +Dentro de un character set , puede definir un rango de caracteres para hacer coincidir usando un carácter de hyphen : - . +Por ejemplo, para que coincida con las letras minúsculas a medio e que usaría [ae] . +
    let catStr = "cat";
    let batStr = "bat";
    let matStr = "mat";
    let bgRegex = /[a-e]at/;
    catStr.match(bgRegex); // Returns ["cat"]
    batStr.match(bgRegex); // Returns ["bat"]
    matStr.match(bgRegex); // Returns null
    +
    + +## Instructions +
    +Coinciden con todas las letras en la cadena quoteSample . +Nota
    Asegúrese de hacer coincidir las letras mayúsculas y minúsculas . 0
    + +## Tests +
    + +```yml +tests: + - text: Su regex alphabetRegex debe coincidir con 35 elementos. + testString: 'assert(result.length == 35, "Your regex alphabetRegex should match 35 items.");' + - text: Su regex alphabetRegex debe usar la bandera global. + testString: 'assert(alphabetRegex.flags.match(/g/).length == 1, "Your regex alphabetRegex should use the global flag.");' + - text: Su regex alphabetRegex debe usar la bandera que no distingue entre mayúsculas y minúsculas. + testString: 'assert(alphabetRegex.flags.match(/i/).length == 1, "Your regex alphabetRegex should use the case insensitive flag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "The quick brown fox jumps over the lazy dog."; +let alphabetRegex = /change/; // Change this line +let result = alphabetRegex; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.spanish.md new file mode 100644 index 0000000000..14d3749d97 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-literal-strings.spanish.md @@ -0,0 +1,61 @@ +--- +id: 587d7db3367417b2b2512b8f +title: Match Literal Strings +localeTitle: Unir cuerdas literales +challengeType: 1 +--- + +## Description +
    +En el último desafío, buscó la palabra "Hello" usando la expresión regular /Hello/ . Esa expresión regular buscó una coincidencia literal de la cadena "Hello" . Aquí hay otro ejemplo que busca una coincidencia literal de la cadena "Kevin" : +
    let testStr = "Hello, my name is Kevin.";
    let testRegex = /Kevin/;
    testRegex.test(testStr);
    // Returns true
    +Cualquier otra forma de "Kevin" no coincidirá. Por ejemplo, la expresión regular /Kevin/ no coincidirá con "kevin" o "KEVIN" . +
    let wrongRegex = /kevin/;
    wrongRegex.test(testStr);
    // Returns false
    +Un desafío futuro mostrará cómo emparejar esas otras formas también. +
    + +## Instructions +
    +Complete la expresión regular waldoRegex para encontrar "Waldo" en la cadena waldoIsHiding con una coincidencia literal. +
    + +## Tests +
    + +```yml +tests: + - text: Tu regex waldoRegex debería encontrar "Waldo" + testString: 'assert(waldoRegex.test(waldoIsHiding), "Your regex waldoRegex should find "Waldo"");' + - text: Su regex waldoRegex no debe buscar nada más. + testString: 'assert(!waldoRegex.test("Somewhere is hiding in this text."), "Your regex waldoRegex should not search for anything else.");' + - text: Debe realizar una coincidencia de cadena literal con su expresión regular. + testString: 'assert(!/\/.*\/i/.test(code), "You should perform a literal string match with your regex.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let waldoIsHiding = "Somewhere Waldo is hiding in this text."; +let waldoRegex = /search/; // Change this line +let result = waldoRegex.test(waldoIsHiding); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.spanish.md new file mode 100644 index 0000000000..249f5017c7 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-non-whitespace-characters.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7db9367417b2b2512ba4 +title: Match Non-Whitespace Characters +localeTitle: Combina caracteres que no sean espacios en blanco +challengeType: 1 +--- + +## Description +
    +Aprendiste sobre la búsqueda de espacios en blanco usando \s , con una s minúscula. También puede buscar todo excepto espacios en blanco. +Busque no espacios en blanco usando \S , que es un s mayúsculas. Este patrón no coincidirá con los espacios en blanco, el retorno de carro, la pestaña, el avance de página y los nuevos caracteres de línea. Puede pensar que es similar a la clase de caracteres [^ \r\t\f\n\v] . +
    let whiteSpace = "Whitespace. Whitespace everywhere!"
    let nonSpaceRegex = /\S/g;
    whiteSpace.match(nonSpaceRegex).length; // Returns 32
    +
    + +## Instructions +
    +Cambie el regex countNonWhiteSpace para buscar múltiples caracteres que no sean espacios en blanco en una cadena. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(countNonWhiteSpace.global, "Your regex should use the global flag.");' + - text: Tu expresión regular debe usar el carácter abreviado + testString: 'assert(/\\S/.test(countNonWhiteSpace.source), "Your regex should use the shorthand character \S/code> to match all non-whitespace characters.");' + - text: Su expresión regular debe encontrar 35 espacios sin espacios en "Los hombres son de Marte y las mujeres son de Venus". + testString: 'assert("Men are from Mars and women are from Venus.".match(countNonWhiteSpace).length == 35, "Your regex should find 35 non-spaces in "Men are from Mars and women are from Venus."");' + - text: 'Su expresión regular debe encontrar 23 espacios sin espacios en "Espacio: la frontera final". ' + testString: 'assert("Space: the final frontier.".match(countNonWhiteSpace).length == 23, "Your regex should find 23 non-spaces in "Space: the final frontier."");' + - text: Su expresión regular debe encontrar 21 espacios sin espacios en "MindYourPersonalSpace" + testString: 'assert("MindYourPersonalSpace".match(countNonWhiteSpace).length == 21, "Your regex should find 21 non-spaces in "MindYourPersonalSpace"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let sample = "Whitespace is important in separating words"; +let countNonWhiteSpace = /change/; // Change this line +let result = sample.match(countNonWhiteSpace); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.spanish.md new file mode 100644 index 0000000000..aa4759d822 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-numbers-and-letters-of-the-alphabet.spanish.md @@ -0,0 +1,60 @@ +--- +id: 587d7db5367417b2b2512b97 +title: Match Numbers and Letters of the Alphabet +localeTitle: Coincidir números y letras del alfabeto +challengeType: 1 +--- + +## Description +
    +uso del guión ( - ) para hacer coincidir un rango de caracteres no se limita a las letras. También funciona para hacer coincidir un rango de números. +Por ejemplo, /[0-5]/ coincide con cualquier número entre 0 y 5 , incluidos 0 y 5 . +Además, es posible combinar un rango de letras y números en un solo conjunto de caracteres. +
    let jennyStr = "Jenny8675309";
    let myRegex = /[a-z0-9]/ig;
    // matches all letters and numbers in jennyStr
    jennyStr.match(myRegex);
    +
    + +## Instructions +
    +Crear una sola expresión regular que coincide con una gama de cartas entre h y s , y una gama de números de entre 2 y 6 . Recuerde incluir las banderas apropiadas en la expresión regular. +
    + +## Tests +
    + +```yml +tests: + - text: Tu regex myRegex debe coincidir con 17 elementos. + testString: 'assert(result.length == 17, "Your regex myRegex should match 17 items.");' + - text: Su regex myRegex debe usar la bandera global. + testString: 'assert(myRegex.flags.match(/g/).length == 1, "Your regex myRegex should use the global flag.");' + - text: Su expresión regular myRegex debe usar la myRegex no distingue entre mayúsculas y minúsculas. + testString: 'assert(myRegex.flags.match(/i/).length == 1, "Your regex myRegex should use the case insensitive flag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "Blueberry 3.141592653s are delicious."; +let myRegex = /change/; // Change this line +let result = myRegex; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.spanish.md new file mode 100644 index 0000000000..549d1f0f6c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-character-with-multiple-possibilities.spanish.md @@ -0,0 +1,65 @@ +--- +id: 587d7db5367417b2b2512b95 +title: Match Single Character with Multiple Possibilities +localeTitle: Coincidir con un solo personaje con múltiples posibilidades +challengeType: 1 +--- + +## Description +
    +Aprendió cómo hacer coincidir patrones literales ( /literal/ ) y caracteres comodín ( /./ ). Esos son los extremos de las expresiones regulares, donde uno encuentra coincidencias exactas y el otro todo. Hay opciones que son un equilibrio entre los dos extremos. +Puede buscar un patrón literal con cierta flexibilidad con las character classes . Las clases de caracteres le permiten definir un grupo de caracteres que desea hacer coincidiendo colocándolos entre corchetes cuadrados ( [ y ] ). +Por ejemplo, desea hacer coincidir "bag" , "big" y "bug" pero no "bog" . Puede crear la expresión regular /b[aiu]g/ para hacer esto. La [aiu] es la clase de caracteres que solo coincidirá con los caracteres "a" , "i" o "u" . +
    let bigStr = "big";
    let bagStr = "bag";
    let bugStr = "bug";
    let bogStr = "bog";
    let bgRegex = /b[aiu]g/;
    bigStr.match(bgRegex); // Returns ["big"]
    bagStr.match(bgRegex); // Returns ["bag"]
    bugStr.match(bgRegex); // Returns ["bug"]
    bogStr.match(bgRegex); // Returns null
    +
    + +## Instructions +
    +Use una clase de caracteres con vocales ( a , e , i , o , u ) en su regex vowelRegex para encontrar todas las vocales en la cadena quoteSample . +Nota
    Asegúrese de hacer coincidir las vocales mayúsculas y minúsculas. +
    + +## Tests +
    + +```yml +tests: + - text: Debes encontrar las 25 vocales. + testString: 'assert(result.length == 25, "You should find all 25 vowels.");' + - text: Su regex vowelRegex debe usar una clase de caracteres. + testString: 'assert(/\[.*\]/.test(vowelRegex.source), "Your regex vowelRegex should use a character class.");' + - text: Su regex vowelRegex debe usar la bandera global. + testString: 'assert(vowelRegex.flags.match(/g/).length == 1, "Your regex vowelRegex should use the global flag.");' + - text: Su regex vowelRegex debe usar la marca que no distingue entre mayúsculas y minúsculas. + testString: 'assert(vowelRegex.flags.match(/i/).length == 1, "Your regex vowelRegex should use the case insensitive flag.");' + - text: Su expresión regular no debe coincidir con ninguna consonante. + testString: 'assert(!/[b-df-hj-np-tv-z]/gi.test(result.join()), "Your regex should not match any consonants.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "Beware of bugs in the above code; I have only proved it correct, not tried it."; +let vowelRegex = /change/; // Change this line +let result = vowelRegex; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.spanish.md new file mode 100644 index 0000000000..a5b510c80c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-single-characters-not-specified.spanish.md @@ -0,0 +1,59 @@ +--- +id: 587d7db6367417b2b2512b98 +title: Match Single Characters Not Specified +localeTitle: Coincidir con caracteres individuales no especificados +challengeType: 1 +--- + +## Description +
    +Hasta ahora, ha creado un conjunto de caracteres que desea hacer coincidir, pero también puede crear un conjunto de caracteres que no desea que coincida. Estos tipos de conjuntos de caracteres se denominan negated character sets . +Para crear un negated character set , coloque un carácter de caret ( ^ ) después del corchete de apertura y antes de los caracteres que no desea que coincidan. +Por ejemplo, /[^aeiou]/gi coincide con todos los caracteres que no son una vocal. Tenga en cuenta que a los personajes les gusta . , ! , [ , @ , / y el espacio en blanco coinciden: el conjunto de caracteres de la vocal negada solo excluye los caracteres de la vocal. +
    + +## Instructions +
    +Cree una expresión regular única que coincida con todos los caracteres que no sean un número o una vocal. Recuerde incluir las banderas apropiadas en la expresión regular. +
    + +## Tests +
    + +```yml +tests: + - text: Tu regex myRegex debe coincidir con 9 elementos. + testString: 'assert(result.length == 9, "Your regex myRegex should match 9 items.");' + - text: Su regex myRegex debe usar la bandera global. + testString: 'assert(myRegex.flags.match(/g/).length == 1, "Your regex myRegex should use the global flag.");' + - text: Su expresión regular myRegex debe usar la myRegex no distingue entre mayúsculas y minúsculas. + testString: 'assert(myRegex.flags.match(/i/).length == 1, "Your regex myRegex should use the case insensitive flag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let quoteSample = "3 blind mice."; +let myRegex = /change/; // Change this line +let result = myRegex; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.spanish.md new file mode 100644 index 0000000000..162982c499 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7db8367417b2b2512ba3 +title: Match Whitespace +localeTitle: Emparejar espacios en blanco +challengeType: 1 +--- + +## Description +
    +Los desafíos hasta ahora han cubierto las letras correspondientes del alfabeto y los números. También puede hacer coincidir los espacios en blanco o espacios entre letras. +Puede buscar espacios en blanco usando \s , que es un s minúscula. Este patrón no solo coincide con el espacio en blanco, sino también con el retorno de carro, la pestaña, el avance de página y los nuevos caracteres de línea. Puede pensar que es similar a la clase de caracteres [ \r\t\f\n\v] . +
    let whiteSpace = "Whitespace. Whitespace everywhere!"
    let spaceRegex = /\s/g;
    whiteSpace.match(spaceRegex);
    // Returns [" ", " "]
    +
    + +## Instructions +
    +Cambie el regex countWhiteSpace para buscar múltiples caracteres de espacio en blanco en una cadena. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar la bandera global. + testString: 'assert(countWhiteSpace.global, "Your regex should use the global flag.");' + - text: Tu expresión regular debe usar el carácter abreviado + testString: 'assert(/\\s/.test(countWhiteSpace.source), "Your regex should use the shorthand character \s to match all whitespace characters.");' + - text: Su expresión regular debe encontrar ocho espacios en "Los hombres son de Marte y las mujeres son de Venus". + testString: 'assert("Men are from Mars and women are from Venus.".match(countWhiteSpace).length == 8, "Your regex should find eight spaces in "Men are from Mars and women are from Venus."");' + - text: 'Tu expresión regular debe encontrar tres espacios en "Espacio: la frontera final." ' + testString: 'assert("Space: the final frontier.".match(countWhiteSpace).length == 3, "Your regex should find three spaces in "Space: the final frontier."");' + - text: Su expresión regular no debe encontrar espacios en "MindYourPersonalSpace" + testString: 'assert("MindYourPersonalSpace".match(countWhiteSpace) == null, "Your regex should find no spaces in "MindYourPersonalSpace"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let sample = "Whitespace is important in separating words"; +let countWhiteSpace = /change/; // Change this line +let result = sample.match(countWhiteSpace); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.spanish.md new file mode 100644 index 0000000000..ef2e6a2e37 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/positive-and-negative-lookahead.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d7dba367417b2b2512ba9 +title: Positive and Negative Lookahead +localeTitle: Lookahead positivo y negativo +challengeType: 1 +--- + +## Description +
    +Lookaheads son patrones que le dicen a JavaScript que mire hacia adelante en su cadena para buscar patrones más adelante. Esto puede ser útil cuando desea buscar múltiples patrones sobre la misma cadena. +Hay dos tipos de lookaheads : positive lookahead y negative lookahead . +Un positive lookahead mirará para asegurarse de que el elemento en el patrón de búsqueda esté allí, pero en realidad no lo coincidirá. Un lookahead positivo se usa como (?=...) donde ... es la parte requerida que no coincide. +Por otro lado, un negative lookahead se verá para asegurarse de que el elemento en el patrón de búsqueda no esté allí. Un lookahead negativo se usa como (?!...) donde el ... es el patrón que no desea que esté allí. El resto del patrón se devuelve si la parte de búsqueda anticipada negativa no está presente. +Lookaheads son un poco confusos, pero algunos ejemplos ayudarán. +
    let quit = "qu";
    let noquit = "qt";
    let quRegex= /q(?=u)/;
    let qRegex = /q(?!u)/;
    quit.match(quRegex); // Returns ["q"]
    noquit.match(qRegex); // Returns ["q"]
    +Un uso más práctico de lookaheads es marcar dos o más patrones en una cadena. Aquí hay un verificador de contraseña (ingenuamente) simple que busca entre 3 y 6 caracteres y al menos un número: +
    let password = "abc123";
    let checkPass = /(?=\w{3,6})(?=\D*\d)/;
    checkPass.test(password); // Returns true
    +
    + +## Instructions +
    +Use lookaheads en el pwRegex para hacer coincidir las contraseñas que tienen más de 5 caracteres y tienen dos dígitos consecutivos. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar dos lookaheads positivos. + testString: 'assert(pwRegex.source.match(/\(\?=.*?\)\(\?=.*?\)/) !== null, "Your regex should use two positive lookaheads.");' + - text: Tu expresión regular no debe coincidir con "astronaut" + testString: 'assert(!pwRegex.test("astronaut"), "Your regex should not match "astronaut"");' + - text: Su expresión regular no debe coincidir con "airplanes" + testString: 'assert(!pwRegex.test("airplanes"), "Your regex should not match "airplanes"");' + - text: Tu expresión regular no debe coincidir con "banan1" + testString: 'assert(!pwRegex.test("banan1"), "Your regex should not match "banan1"");' + - text: Tu expresión regular debe coincidir con "bana12" + testString: 'assert(pwRegex.test("bana12"), "Your regex should match "bana12"");' + - text: Tu expresión regular debe coincidir con "abc123" + testString: 'assert(pwRegex.test("abc123"), "Your regex should match "abc123"");' + - text: Su expresión regular no debe coincidir con "123" + testString: 'assert(!pwRegex.test("123"), "Your regex should not match "123"");' + - text: Su expresión regular no debe coincidir con "1234" + testString: 'assert(!pwRegex.test("1234"), "Your regex should not match "1234"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let sampleWord = "astronaut"; +let pwRegex = /change/; // Change this line +let result = pwRegex.test(sampleWord); +``` + +
    + + + +
    + +## Solution +
    + + +```js +var pwRegex = /(?=\w{5})(?=\D*\d{2})/; +``` + +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.spanish.md new file mode 100644 index 0000000000..8554225551 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/remove-whitespace-from-start-and-end.spanish.md @@ -0,0 +1,58 @@ +--- +id: 587d7dbb367417b2b2512bac +title: Remove Whitespace from Start and End +localeTitle: Eliminar espacios en blanco de inicio y fin +challengeType: 1 +--- + +## Description +
    +A veces, los caracteres de espacios en blanco alrededor de las cadenas no son deseados pero están ahí. El procesamiento típico de las cadenas es eliminar el espacio en blanco al principio y al final. +
    + +## Instructions +
    +Escriba una expresión regular y use los métodos de cadena apropiados para eliminar los espacios en blanco al principio y al final de las cadenas. +Nota
    El método .trim() funcionaría aquí, pero necesitarás completar este desafío usando expresiones regulares. +
    + +## Tests +
    + +```yml +tests: + - text: El result debería ser igual a "Hello, World!" ' + testString: 'assert(result == "Hello, World!", "result should equal to "Hello, World!"");' + - text: No debes usar el método .trim() . + testString: 'assert(!code.match(/\.trim\(.*?\)/), "You should not use the .trim() method.");' + - text: La variable de result no debe ser igual a una cadena. + testString: 'assert(!code.match(/result\s*=\s*".*?"/), "The result variable should not be set equal to a string.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let hello = " Hello, World! "; +let wsRegex = /change/; // Change this line +let result = hello; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.spanish.md new file mode 100644 index 0000000000..909930ca1c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/restrict-possible-usernames.spanish.md @@ -0,0 +1,67 @@ +--- +id: 587d7db8367417b2b2512ba2 +title: Restrict Possible Usernames +localeTitle: Restringir posibles nombres de usuario +challengeType: 1 +--- + +## Description +
    +nombres de usuario se utilizan en todas partes en Internet. Son los que dan a los usuarios una identidad única en sus sitios favoritos. +Es necesario comprobar todos los nombres de usuario en una base de datos. Aquí hay algunas reglas simples que los usuarios deben seguir al crear su nombre de usuario. +1) Los únicos números en el nombre de usuario deben estar al final. Puede haber cero o más de ellos al final. +2) Las letras de los nombres de usuario pueden estar en minúsculas y mayúsculas. +3) Los nombres de usuario deben tener al menos dos caracteres. Un nombre de usuario de dos letras solo puede usar caracteres de letras del alfabeto. +
    + +## Instructions +
    +Cambie el regex userCheck para que se ajuste a las restricciones enumeradas anteriormente. +
    + +## Tests +
    + +```yml +tests: + - text: Tu expresión regular debe coincidir con JACK + testString: 'assert(userCheck.test("JACK"), "Your regex should match JACK");' + - text: Tu expresión regular no debe coincidir con J + testString: 'assert(!userCheck.test("J"), "Your regex should not match J");' + - text: Tu expresión regular debe coincidir con Oceans11 + testString: 'assert(userCheck.test("Oceans11"), "Your regex should match Oceans11");' + - text: Tu expresión regular debe coincidir con RegexGuru + testString: 'assert(userCheck.test("RegexGuru"), "Your regex should match RegexGuru");' + - text: Su expresión regular no debe coincidir con 007 + testString: 'assert(!userCheck.test("007"), "Your regex should not match 007");' + - text: Tu expresión regular no debe coincidir con 9 + testString: 'assert(!userCheck.test("9"), "Your regex should not match 9");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let username = "JackOfAllTrades"; +let userCheck = /change/; // Change this line +let result = userCheck.test(username); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups.spanish.md new file mode 100644 index 0000000000..1919972608 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups.spanish.md @@ -0,0 +1,76 @@ +--- +id: 587d7dbb367417b2b2512baa +title: Reuse Patterns Using Capture Groups +localeTitle: Reutilizar patrones usando grupos de captura +challengeType: 1 +--- + +## Description +
    +Algunos patrones que busca ocurrirán varias veces en una cadena. Es un desperdicio repetir manualmente la expresión regular. Hay una mejor manera de especificar cuándo tiene varias subcadenas de repetición en su cadena. +Puede buscar subcadenas repetidas usando capture groups . Los paréntesis, ( y ) , se utilizan para encontrar subcadenas repetidas. Pones la expresión regular del patrón que se repetirá entre paréntesis. +Para especificar dónde aparecerá esa cadena de repetición, use una barra diagonal inversa ( \ ) y luego un número. Este número comienza en 1 y aumenta con cada grupo de captura adicional que use. Un ejemplo sería \1 para que coincida con el primer grupo. +El siguiente ejemplo coincide con cualquier palabra que aparezca dos veces separadas por un espacio: +
    let repeatStr = "regex regex";
    let repeatRegex = /(\w+)\s\1/;
    repeatRegex.test(repeatStr); // Returns true
    repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"]
    +uso del método .match() en una cadena devolverá una matriz con la cadena que coincide, junto con su grupo de captura. +
    + +## Instructions +
    +Use los capture groups en reRegex para hacer coincidir los números que se repiten solo tres veces en una cadena, cada uno separado por un espacio. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe usar la clase de caracteres abreviados para los dígitos. + testString: 'assert(reRegex.source.match(/\\d/), "Your regex should use the shorthand character class for digits.");' + - text: Su expresión regular debe reutilizar el grupo de captura dos veces. + testString: 'assert(reRegex.source.match(/\\\d/g).length === 2, "Your regex should reuse the capture group twice.");' + - text: Su expresión regular debe tener dos espacios que separan los tres números. + testString: 'assert(reRegex.source.match(/\\s/g).length === 2, "Your regex should have two spaces separating the three numbers.");' + - text: Su expresión regular debe coincidir con "42 42 42" . + testString: 'assert(reRegex.test("42 42 42"), "Your regex should match "42 42 42".");' + - text: Su expresión regular debe coincidir con "100 100 100" . + testString: 'assert(reRegex.test("100 100 100"), "Your regex should match "100 100 100".");' + - text: Su expresión regular no debe coincidir con "42 42 42 42" . + testString: 'assert.equal(("42 42 42 42").match(reRegex.source), null, "Your regex should not match "42 42 42 42".");' + - text: Su expresión regular no debe coincidir con "42 42" . + testString: 'assert.equal(("42 42").match(reRegex.source), null, "Your regex should not match "42 42".");' + - text: Su expresión regular no debe coincidir con "101 102 103" . + testString: 'assert(!reRegex.test("101 102 103"), "Your regex should not match "101 102 103".");' + - text: Su expresión regular no debe coincidir con "1 2 3" . + testString: 'assert(!reRegex.test("1 2 3"), "Your regex should not match "1 2 3".");' + - text: Su expresión regular debe coincidir con "10 10 10" . + testString: 'assert(reRegex.test("10 10 10"), "Your regex should match "10 10 10".");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let repeatNum = "42 42 42"; +let reRegex = /change/; // Change this line +let result = reRegex.test(repeatNum); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.spanish.md new file mode 100644 index 0000000000..207e256e89 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-exact-number-of-matches.spanish.md @@ -0,0 +1,66 @@ +--- +id: 587d7db9367417b2b2512ba7 +title: Specify Exact Number of Matches +localeTitle: Especifique el número exacto de coincidencias +challengeType: 1 +--- + +## Description +
    +Puede especificar el número inferior y superior de patrones con quantity specifiers utilizando llaves. A veces solo quieres un número específico de coincidencias. +Para especificar un cierto número de patrones, solo tiene ese número entre las llaves. +Por ejemplo, para hacer coincidir solo la palabra "hah" con la letra a 3 veces, su expresión regular sería /ha{3}h/ . +
    let A4 = "haaaah";
    let A3 = "haaah";
    let A100 = "h" + "a".repeat(100) + "h";
    let multipleHA = /ha{3}h/;
    multipleHA.test(A4); // Returns false
    multipleHA.test(A3); // Returns true
    multipleHA.test(A100); // Returns false
    +
    + +## Instructions +
    +Cambie el regex timRegex para que coincida con la palabra "Timber" solo cuando tenga cuatro letras m . +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar llaves. + testString: 'assert(timRegex.source.match(/{.*?}/).length > 0, "Your regex should use curly brackets.");' + - text: Su expresión regular no debe coincidir con "Timber" + testString: 'assert(!timRegex.test("Timber"), "Your regex should not match "Timber"");' + - text: Su expresión regular no debe coincidir con "Timmber" + testString: 'assert(!timRegex.test("Timmber"), "Your regex should not match "Timmber"");' + - text: Su expresión regular no debe coincidir con "Timmmber" + testString: 'assert(!timRegex.test("Timmmber"), "Your regex should not match "Timmmber"");' + - text: Su expresión regular debe coincidir con "Timmmmber" + testString: 'assert(timRegex.test("Timmmmber"), "Your regex should match "Timmmmber"");' + - text: Su expresión regular no debe coincidir con "Timber" con 30 m en ella. + testString: 'assert(!timRegex.test("Ti" + "m".repeat(30) + "ber"), "Your regex should not match "Timber" with 30 m\"s in it.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let timStr = "Timmmmber"; +let timRegex = /change/; // Change this line +let result = timRegex.test(timStr); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.spanish.md new file mode 100644 index 0000000000..06dec3ad1c --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-only-the-lower-number-of-matches.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7db9367417b2b2512ba6 +title: Specify Only the Lower Number of Matches +localeTitle: Especifique solo el número inferior de coincidencias +challengeType: 1 +--- + +## Description +
    +Puede especificar el número inferior y superior de patrones con quantity specifiers utilizando llaves. A veces solo desea especificar el número más bajo de patrones sin límite superior. +Para especificar solo el número más bajo de patrones, mantenga el primer número seguido de una coma. +Por ejemplo, para hacer coincidir solo la cadena "hah" con la letra a aparece al menos 3 veces, su expresión regular sería /ha{3,}h/ . +
    let A4 = "haaaah";
    let A2 = "haah";
    let A100 = "h" + "a".repeat(100) + "h";
    let multipleA = /ha{3,}h/;
    multipleA.test(A4); // Returns true
    multipleA.test(A2); // Returns false
    multipleA.test(A100); // Returns true
    +
    + +## Instructions +
    +Cambie el regex haRegex para que coincida con la palabra "Hazzah" solo cuando tenga cuatro o más letras z 's. +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar llaves. + testString: 'assert(haRegex.source.match(/{.*?}/).length > 0, "Your regex should use curly brackets.");' + - text: Su expresión regular no debe coincidir con "Hazzah" + testString: 'assert(!haRegex.test("Hazzah"), "Your regex should not match "Hazzah"");' + - text: Su expresión regular no debe coincidir con "Hazzzah" + testString: 'assert(!haRegex.test("Hazzzah"), "Your regex should not match "Hazzzah"");' + - text: Su expresión regular debe coincidir con "Hazzzzah" + testString: 'assert(haRegex.test("Hazzzzah"), "Your regex should match "Hazzzzah"");' + - text: Su expresión regular debe coincidir con "Hazzzzzah" + testString: 'assert(haRegex.test("Hazzzzzah"), "Your regex should match "Hazzzzzah"");' + - text: Su expresión regular debe coincidir con "Hazzzzzzah" + testString: 'assert(haRegex.test("Hazzzzzzah"), "Your regex should match "Hazzzzzzah"");' + - text: Su expresión regular debe coincidir con "Hazzah" con 30 z \ 's en ella. + testString: 'assert(haRegex.test("Ha" + "z".repeat(30) + "ah"), "Your regex should match "Hazzah" with 30 z\"s in it.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let haStr = "Hazzzzah"; +let haRegex = /change/; // Change this line +let result = haRegex.test(haStr); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.spanish.md new file mode 100644 index 0000000000..4f5fc357a5 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/specify-upper-and-lower-number-of-matches.spanish.md @@ -0,0 +1,68 @@ +--- +id: 587d7db9367417b2b2512ba5 +title: Specify Upper and Lower Number of Matches +localeTitle: Especifique el número superior e inferior de coincidencias +challengeType: 1 +--- + +## Description +
    +Recuerde que usa el signo más + para buscar uno o más caracteres y el asterisco * para buscar cero o más caracteres. Estos son convenientes, pero a veces usted quiere hacer coincidir un cierto rango de patrones. +Puede especificar el número inferior y superior de patrones con quantity specifiers . Los especificadores de cantidad se utilizan con llaves ( { y } ). Pones dos números entre las llaves: para el número inferior y superior de patrones. +Por ejemplo, para hacer coincidir solo la letra a aparece entre 3 y 5 veces en la cadena "ah" , su expresión regular sería /a{3,5}h/ . +
    let A4 = "aaaah";
    let A2 = "aah";
    let multipleA = /a{3,5}h/;
    multipleA.test(A4); // Returns true
    multipleA.test(A2); // Returns false
    +
    + +## Instructions +
    +Cambie el regex ohRegex para que coincida solo con 3 a 6 letras h en la palabra "Oh no" . +
    + +## Tests +
    + +```yml +tests: + - text: Su expresión regular debe utilizar llaves. + testString: 'assert(ohRegex.source.match(/{.*?}/).length > 0, "Your regex should use curly brackets.");' + - text: Su expresión regular no debe coincidir con "Ohh no" + testString: 'assert(!ohRegex.test("Ohh no"), "Your regex should not match "Ohh no"");' + - text: Su expresión regular debe coincidir con "Ohhh no" + testString: 'assert(ohRegex.test("Ohhh no"), "Your regex should match "Ohhh no"");' + - text: Su expresión regular debe coincidir con "Ohhhh no" + testString: 'assert(ohRegex.test("Ohhhh no"), "Your regex should match "Ohhhh no"");' + - text: Su expresión regular debe coincidir con "Ohhhhh no" + testString: 'assert(ohRegex.test("Ohhhhh no"), "Your regex should match "Ohhhhh no"");' + - text: Su expresión regular debe coincidir con "Ohhhhhh no" + testString: 'assert(ohRegex.test("Ohhhhhh no"), "Your regex should match "Ohhhhhh no"");' + - text: Su expresión regular no debe coincidir con "Ohhhhhhh no" + testString: 'assert(!ohRegex.test("Ohhhhhhh no"), "Your regex should not match "Ohhhhhhh no"");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let ohStr = "Ohhh no"; +let ohRegex = /change/; // Change this line +let result = ohRegex.test(ohStr); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.spanish.md new file mode 100644 index 0000000000..79f3a5f916 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/use-capture-groups-to-search-and-replace.spanish.md @@ -0,0 +1,63 @@ +--- +id: 587d7dbb367417b2b2512bab +title: Use Capture Groups to Search and Replace +localeTitle: Utilice los grupos de captura para buscar y reemplazar +challengeType: 1 +--- + +## Description +
    +búsqueda es útil. Sin embargo, puede hacer que la búsqueda sea aún más poderosa cuando también cambia (o reemplaza) el texto que coincide. +Puede buscar y reemplazar texto en una cadena usando .replace() en una cadena. Las entradas para .replace() son primero el patrón de .replace() regulares que desea buscar. El segundo parámetro es la cadena para reemplazar la coincidencia o una función para hacer algo. +
    let wrongText = "The sky is silver.";
    let silverRegex = /silver/;
    wrongText.replace(silverRegex, "blue");
    // Returns "The sky is blue."
    +También puede acceder a grupos de captura en la cadena de reemplazo con signos de dólar ( $ ). +
    "Code Camp".replace(/(\w+)\s(\w+)/, '$2 +');
    // Returns "Camp Code"
    +
    + +## Instructions +
    +Escriba una expresión regular para que busque la cadena "good" . Luego actualice la variable replaceText para reemplazar "good" con "okey-dokey" . +
    + +## Tests +
    + +```yml +tests: + - text: Debes usar .replace() para buscar y reemplazar. + testString: 'assert(code.match(/\.replace\(.*\)/), "You should use .replace() to search and replace.");' + - text: Tu expresión regular debería cambiar "This sandwich is good." a "This sandwich is okey-dokey." + testString: 'assert(result == "This sandwich is okey-dokey." && replaceText === "okey-dokey", "Your regex should change "This sandwich is good." to "This sandwich is okey-dokey."");' + - text: No debes cambiar la última línea. + testString: 'assert(code.match(/result\s*=\s*huhText\.replace\(.*?\)/), "You should not change the last line.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let huhText = "This sandwich is good."; +let fixRegex = /change/; // Change this line +let replaceText = ""; // Change this line +let result = huhText.replace(fixRegex, replaceText); +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.spanish.md b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.spanish.md new file mode 100644 index 0000000000..df60a38a68 --- /dev/null +++ b/curriculum/challenges/spanish/02-javascript-algorithms-and-data-structures/regular-expressions/using-the-test-method.spanish.md @@ -0,0 +1,58 @@ +--- +id: 587d7db3367417b2b2512b8e +title: Using the Test Method +localeTitle: Usando el Método de Prueba +challengeType: 1 +--- + +## Description +
    +Las expresiones regulares se usan en lenguajes de programación para hacer coincidir partes de cadenas. Creas patrones para ayudarte a hacer ese emparejamiento. +Si desea buscar la palabra "the" en la cadena "The dog chased the cat" , puede usar la siguiente expresión regular: /the/ . Observe que las comillas no son necesarias dentro de la expresión regular. +JavaScript tiene múltiples formas de usar expresiones regulares. Una forma de probar una expresión regular es mediante el método .test() . El método .test() toma la expresión regular, la aplica a una cadena (que se coloca entre paréntesis) y devuelve true o false si su patrón encuentra algo o no. +
    let testStr = "freeCodeCamp";
    let testRegex = /Code/;
    testRegex.test(testStr);
    // Returns true
    +
    + +## Instructions +
    +Aplique el regex myRegex en la cadena myString usando el método .test() . +
    + +## Tests +
    + +```yml +tests: + - text: Debe usar .test() para probar la expresión regular. + testString: 'assert(code.match(/myRegex.test\(\s*myString\s*\)/), "You should use .test() to test the regex.");' + - text: Su resultado debe devolver true . + testString: 'assert(result === true, "Your result should return true.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```js +let myString = "Hello, World!"; +let myRegex = /Hello/; +let result = myRegex; // Change this line +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-elements-within-your-bootstrap-wells.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-elements-within-your-bootstrap-wells.spanish.md new file mode 100644 index 0000000000..feefd0727c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-elements-within-your-bootstrap-wells.spanish.md @@ -0,0 +1,74 @@ +--- +id: bad87fee1348bd9aec908849 +title: Add Elements within Your Bootstrap Wells +localeTitle: Agrega elementos dentro de tus pozos de Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora somos varios elementos div en cada columna de nuestra fila. Esto es tan profundo como tendremos que ir. Ahora podemos añadir nuestros elementos de button . +Anide tres elementos de button dentro de cada uno de sus elementos de well div . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Anida tres elementos de button dentro de cada uno de tus elementos div con clase well . + testString: 'assert($("div.well:eq(0)").children("button").length === 3 && $("div.well:eq(1)").children("button").length === 3, "Nest three button elements within each of your div elements with class well.");' + - text: Debes tener un total de 6 elementos de button . + testString: 'assert($("button") && $("button").length > 5, "You should have a total of 6 button elements.");' + - text: Asegúrese de que todos los elementos de sus button tengan etiquetas de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-all-of-our-buttons.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-all-of-our-buttons.spanish.md new file mode 100644 index 0000000000..9e2084207a --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-all-of-our-buttons.spanish.md @@ -0,0 +1,116 @@ +--- +id: bad87fee1348bd9aedc08845 +title: Add Font Awesome Icons to all of our Buttons +localeTitle: Añadir iconos impresionantes de fuente a todos nuestros botones +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +Font Awesome es una conveniente biblioteca de iconos. Estos iconos son gráficos vectoriales, almacenados en el formato de archivo .svg . Estos iconos son tratados como fuentes. Puede especificar su tamaño usando píxeles, y asumirán el tamaño de fuente de sus elementos HTML principales. +Use Font Awesome para agregar un ícono de info-circle de información a su botón de información y un ícono de trash a su botón de eliminar. +Nota: El elemento span es una alternativa aceptable al elemento i para las instrucciones a continuación. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Debes agregar un <i class="fa fa-info-circle"></i> dentro del elemento de tu botón de información.' + testString: 'assert($(".btn-info > i").is(".fa.fa-info-circle") || $(".btn-info > span").is(".fa.fa-info-circle"), "You should add a <i class="fa fa-info-circle"></i> within your info button element.");' + - text: 'Debes agregar una <i class="fa fa-trash"></i> dentro de tu elemento de botón de eliminar.' + testString: 'assert($(".btn-danger > i").is(".fa.fa-trash") || $(".btn-danger > span").is(".fa.fa-trash"), "You should add a <i class="fa fa-trash"></i> within your delete button element.");' + - text: 'Asegúrate de que cada uno de tus elementos i tenga una etiqueta de cierre y <i class="fa fa-thumbs-up"></i> está en el elemento de tu botón me gusta.' + testString: 'assert(code.match(/<\/i>|<\/span/g) && code.match(/<\/i|<\/span>/g).length > 2 && ($(".btn-primary > i").is(".fa.fa-thumbs-up") || $(".btn-primary > span").is(".fa.fa-thumbs-up")), "Make sure each of your i elements has a closing tag and <i class="fa fa-thumbs-up"></i> is in your like button element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-our-buttons.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-our-buttons.spanish.md new file mode 100644 index 0000000000..16b3c5e161 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-font-awesome-icons-to-our-buttons.spanish.md @@ -0,0 +1,123 @@ +--- +id: bad87fee1348bd9aedd08845 +title: Add Font Awesome Icons to our Buttons +localeTitle: Añadir iconos impresionantes de fuente a nuestros botones +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +Font Awesome es una conveniente biblioteca de iconos. Estos iconos son gráficos vectoriales, almacenados en el formato de archivo .svg . Estos iconos son tratados como fuentes. Puede especificar su tamaño usando píxeles, y asumirán el tamaño de fuente de sus elementos HTML principales. +Puede incluir Font Awesome en cualquier aplicación agregando el siguiente código en la parte superior de su HTML: +<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous"> +En este caso, hemos tenido un gran <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" integrity="sha384-XdYbMnZ/QjLh6iI4ogqCTaIjrFk87ip+ekIjefZch0Y+PvJ8CDYtEs1ipDmPorQ+" crossorigin="anonymous"> . +El elemento i se usó originalmente para hacer otros elementos en cursiva, pero ahora se usa comúnmente para los iconos. Puede agregar las clases de Font Awesome al elemento i para convertirlo en un icono, por ejemplo: +<i class="fa fa-info-circle"></i> +Tenga en cuenta que el elemento span también es aceptable para su uso con iconos +Use Font Awesome para agregar un ícono con el thumbs-up al botón Me gusta dándole un elemento i con las clases fa y fa-thumbs-up ; Asegúrese de mantener el texto "Me gusta" junto al icono. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Agregue un elemento i con las clases fa y fa-thumbs-up . + testString: 'assert($("i").is(".fa.fa-thumbs-up") || $("span").is(".fa.fa-thumbs-up"), "Add an i element with the classes fa and fa-thumbs-up.");' + - text: Tu ícono de fa-thumbs-up debe estar ubicado dentro del botón "Me gusta". + testString: 'assert(($("i.fa-thumbs-up").parent().text().match(/Like/gi) && $(".btn-primary > i").is(".fa.fa-thumbs-up")) || ($("span.fa-thumbs-up").parent().text().match(/Like/gi) && $(".btn-primary > span").is(".fa.fa-thumbs-up")), "Your fa-thumbs-up icon should be located within the Like button.");' + - text: Anida tu elemento i dentro de tu elemento button . + testString: 'assert($("button").children("i").length > 0 || $("button").children("span").length > 0, "Nest your i element within your button element.");' + - text: Asegúrese de que su elemento de icono tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/i>|<\/span>/g), "Make sure your icon element has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-id-attributes-to-bootstrap-elements.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-id-attributes-to-bootstrap-elements.spanish.md new file mode 100644 index 0000000000..0a277e53bb --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/add-id-attributes-to-bootstrap-elements.spanish.md @@ -0,0 +1,76 @@ +--- +id: bad87fee1348bd9aec908853 +title: Add id Attributes to Bootstrap Elements +localeTitle: Añadir atributos de ID a los elementos Bootstrap +challengeType: 0 +--- + +## Description +
    +Recuerde que además de los atributos de clase, puede asignar a cada uno de sus elementos un atributo id . +Cada ID debe ser único para un elemento específico y se debe utilizar solo una vez por página. +Demos una identificación única a cada uno de nuestros elementos div de clase well . +Recuerda que puedes darle a un elemento una identificación como esta: +<div class="well" id="center-well"> +Dale al pozo de la izquierda el id del left-well . Dale al pozo de la derecha la identificación del right-well . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Darle a su izquierda well el id de left-well . + testString: 'assert($(".col-xs-6").children("#left-well") && $(".col-xs-6").children("#left-well").length > 0, "Give your left well the id of left-well.");' + - text: Dar a su derecha well el id de right-well . + testString: 'assert($(".col-xs-6").children("#right-well") && $(".col-xs-6").children("#right-well").length > 0, "Give your right well the id of right-well.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/apply-the-default-bootstrap-button-style.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/apply-the-default-bootstrap-button-style.spanish.md new file mode 100644 index 0000000000..2dcb0abf81 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/apply-the-default-bootstrap-button-style.spanish.md @@ -0,0 +1,73 @@ +--- +id: bad87fee1348bd9aec908850 +title: Apply the Default Bootstrap Button Style +localeTitle: Aplicar el estilo de botón predeterminado Bootstrap +challengeType: 0 +guideUrl: 'https://spanish.freecodecamp.org/guide/certificates/apply-the-default-bootstrap-button-style' +--- + +## Description +
    +Bootstrap tiene otra clase de botón llamada btn-default . +Aplique las clases btn y btn-default a cada uno de los elementos de sus button . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Aplica la clase btn a cada uno de los elementos de tu button . + testString: 'assert($(".btn").length > 5, "Apply the btn class to each of your button elements.");' + - text: Aplique la clase btn-default a cada uno de los elementos de sus button . + testString: 'assert($(".btn-default").length > 5, "Apply the btn-default class to each of your button elements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/call-out-optional-actions-with-btn-info.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/call-out-optional-actions-with-btn-info.spanish.md new file mode 100644 index 0000000000..2d16bb1878 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/call-out-optional-actions-with-btn-info.spanish.md @@ -0,0 +1,116 @@ +--- +id: bad87fee1348cd8acef08813 +title: Call out Optional Actions with btn-info +localeTitle: Llama a acciones opcionales con btn-info +challengeType: 0 +--- + +## Description +
    +Bootstrap viene con varios colores predefinidos para botones. La clase btn-info se utiliza para llamar la atención sobre acciones opcionales que el usuario puede realizar. +Cree un nuevo botón Bootstrap a nivel de bloque debajo de su botón "Me gusta" con el texto "Información", y agregue las clases btn-info y btn-block Bootstrap. +Tenga en cuenta que estos botones aún necesitan las clases btn y btn-block . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Crea un nuevo elemento de button con el texto "Información". + testString: 'assert(new RegExp("info","gi").test($("button").text()), "Create a new button element with the text "Info".");' + - text: Ambos botones de Bootstrap deberían tener las clases btn y btn-block . + testString: 'assert($("button.btn-block.btn").length > 1, "Both of your Bootstrap buttons should have the btn and btn-block classes.");' + - text: Tu nuevo botón debe tener la clase btn-info . + testString: 'assert($("button").hasClass("btn-info"), "Your new button should have the class btn-info.");' + - text: Asegúrese de que todos los elementos de sus button tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/center-text-with-bootstrap.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/center-text-with-bootstrap.spanish.md new file mode 100644 index 0000000000..e4bc71a6ac --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/center-text-with-bootstrap.spanish.md @@ -0,0 +1,111 @@ +--- +id: bad87fee1348bd8acde08812 +title: Center Text with Bootstrap +localeTitle: Centro de texto con Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora que estamos usando Bootstrap, podemos centrar nuestro elemento de encabezado para que se vea mejor. Todo lo que necesitamos hacer es agregar la clase text-center a nuestro elemento h2 . +Recuerde que puede agregar varias clases al mismo elemento separando cada una de ellas con un espacio, como este: +<h2 class="red-text text-center">your text</h2> +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Tu elemento h2 debe centrarse aplicando el text-center la clase + testString: 'assert($("h2").hasClass("text-center"), "Your h2 element should be centered by applying the class text-center");' + - text: Tu elemento h2 todavía debería tener la clase red-text + testString: 'assert($("h2").hasClass("red-text"), "Your h2 element should still have the class red-text");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-block-element-bootstrap-button.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-block-element-bootstrap-button.spanish.md new file mode 100644 index 0000000000..8a077aa685 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-block-element-bootstrap-button.spanish.md @@ -0,0 +1,121 @@ +--- +id: bad87fee1348cd8acef08812 +title: Create a Block Element Bootstrap Button +localeTitle: Crear un botón de arranque Bootstrap Button +challengeType: 0 +--- + +## Description +
    +Normalmente, los elementos de sus button con las clases btn y btn-default son tan anchos como el texto que contienen. Por ejemplo: +<button class="btn btn-default">Submit</button> +Este botón solo será tan ancho como la palabra "Enviar". + +Al convertirlos en elementos de bloque con la clase adicional de btn-block , su botón se expandirá para llenar todo el espacio horizontal de su página y cualquier elemento que se siga fluirá hacia una "nueva línea" debajo del bloque. +<button class="btn btn-default btn-block">Submit</button> +Este botón ocuparía el 100% del ancho disponible. + +Tenga en cuenta que estos botones todavía necesitan la clase btn . +Agregue la clase btn-block de Bootstrap a su botón Bootstrap. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su botón aún debe tener las clases btn y btn-default . + testString: 'assert($("button").hasClass("btn") && $("button").hasClass("btn-default"), "Your button should still have the btn and btn-default classes.");' + - text: Tu botón debe tener la clase btn-block . + testString: 'assert($("button").hasClass("btn-block"), "Your button should have the class btn-block.");' + - text: Asegúrese de que todos los elementos de sus button tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-button.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-button.spanish.md new file mode 100644 index 0000000000..52f243bd9c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-button.spanish.md @@ -0,0 +1,113 @@ +--- +id: bad87fee1348cd8acdf08812 +title: Create a Bootstrap Button +localeTitle: Crear un botón de arranque +challengeType: 0 +--- + +## Description +
    +Bootstrap tiene sus propios estilos para elementos de button , que se ven mucho mejor que los de HTML simple. +Crea un nuevo elemento de button debajo de tu foto grande de gatito. Asígnele las clases btn y btn-default , así como el texto de "Me gusta". +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Crea un nuevo elemento de button con el texto "Me gusta". + testString: 'assert(new RegExp("like","gi").test($("button").text()) && ($("img.img-responsive + button.btn").length > 0), "Create a new button element with the text "Like".");' + - text: 'Su nuevo botón debe tener dos clases: btn y btn-default .' + testString: 'assert($("button").hasClass("btn") && $("button").hasClass("btn-default"), "Your new button should have two classes: btn and btn-default.");' + - text: Asegúrese de que todos los elementos de sus button tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-headline.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-headline.spanish.md new file mode 100644 index 0000000000..cc42f7536e --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-headline.spanish.md @@ -0,0 +1,62 @@ +--- +id: bad87fee1348bd9aec908846 +title: Create a Bootstrap Headline +localeTitle: Crear un título de Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora vamos a construir algo desde cero para practicar nuestras habilidades HTML, CSS y Bootstrap. +Construiremos un patio de juegos de jQuery, que pronto utilizaremos en nuestros desafíos de jQuery. +Para empezar, cree un elemento h3 , con el texto jQuery Playground . +Colorea tu elemento h3 con la clase Bootstrap text-primary del text-primary céntrala con la clase Bootstrap del centro de text-center . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Agrega un elemento h3 a tu página. + testString: 'assert($("h3") && $("h3").length > 0, "Add a h3 element to your page.");' + - text: Asegúrese de que su elemento h3 tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/h3>/g) && code.match(/

    /g).length === code.match(/

    h3 element has a closing tag.");' + - text: Tu elemento h3 debe colorearse aplicando la clase text-primary + testString: 'assert($("h3").hasClass("text-primary"), "Your h3 element should be colored by applying the class text-primary");' + - text: Tu elemento h3 se debe centrar aplicando el text-center la clase + testString: 'assert($("h3").hasClass("text-center"), "Your h3 element should be centered by applying the class text-center");' + - text: Tu elemento h3 debe tener el texto jQuery Playground . + testString: 'assert.isTrue((/jquery(\s)+playground/gi).test($("h3").text()), "Your h3 element should have the text jQuery Playground.");' + +``` + +

    + +## Challenge Seed +
    + +
    + +```html + +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-row.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-row.spanish.md new file mode 100644 index 0000000000..c0d609cd61 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-bootstrap-row.spanish.md @@ -0,0 +1,62 @@ +--- +id: bad87fee1348bd9bec908846 +title: Create a Bootstrap Row +localeTitle: Crear una fila Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora crearemos una fila Bootstrap para nuestros elementos en línea. +Crea un elemento div debajo de la etiqueta h3 , con una clase de row . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Agrega un elemento div debajo de tu elemento h3 . + testString: 'assert(($("div").length > 1) && ($("div.row h3.text-primary").length == 0) && ($("div.row + h3.text-primary").length == 0) && ($("h3.text-primary + div.row").length > 0), "Add a div element below your h3 element.");' + - text: Tu elemento div debe tener la row clase + testString: 'assert($("div").hasClass("row"), "Your div element should have the class row");' + - text: Su row div debe estar anidada dentro de la container-fluid div + testString: 'assert($("div.container-fluid div.row").length > 0, "Your row div should be nested inside the container-fluid div");' + - text: Asegúrese de que su elemento div tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div element has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    + +
    + +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-class-to-target-with-jquery-selectors.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-class-to-target-with-jquery-selectors.spanish.md new file mode 100644 index 0000000000..961bfe7674 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-class-to-target-with-jquery-selectors.spanish.md @@ -0,0 +1,70 @@ +--- +id: bad87fee1348bd9aec908852 +title: Create a Class to Target with jQuery Selectors +localeTitle: Crea una clase para apuntar con los selectores jQuery +challengeType: 0 +--- + +## Description +
    +No todas las clases necesitan tener CSS correspondiente. A veces creamos clases con el único fin de seleccionar estos elementos más fácilmente utilizando jQuery. +Da a cada uno de los elementos de tu button el target la clase. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Aplica la clase target a cada uno de los elementos de tu button . + testString: 'assert($(".target").length > 5, "Apply the target class to each of your button elements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +
    + + + +
    +
    +
    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-custom-heading.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-custom-heading.spanish.md new file mode 100644 index 0000000000..25d5c9c9fc --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-a-custom-heading.spanish.md @@ -0,0 +1,113 @@ +--- +id: bad87fee1348bd9aede08845 +title: Create a Custom Heading +localeTitle: Crear un título personalizado +challengeType: 0 +--- + +## Description +
    +Haremos un encabezado simple para nuestra aplicación de foto Cat colocando el título y la imagen relajante del gato en la misma fila. +Recuerde, Bootstrap utiliza un sistema de cuadrícula sensible, lo que facilita colocar los elementos en filas y especificar el ancho relativo de cada elemento. La mayoría de las clases de Bootstrap se pueden aplicar a un elemento div . +Anide su primera imagen y su elemento h2 dentro de un único elemento <div class="row"> . Anide su elemento h2 dentro de un <div class="col-xs-8"> y su imagen en un <div class="col-xs-4"> para que estén en la misma línea. +¿Observa cómo la imagen tiene el tamaño justo para encajar en el texto? +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento h2 y el elemento img superior deben estar anidados juntos dentro de un elemento div con la row clase. + testString: 'assert($("div.row:has(h2)").length > 0 && $("div.row:has(img)").length > 0, "Your h2 element and topmost img element should both be nested together within a div element with the class row.");' + - text: Anida tu elemento img superior dentro de un div con la clase col-xs-4 . + testString: 'assert($("div.col-xs-4:has(img)").length > 0 && $("div.col-xs-4:has(div)").length === 0, "Nest your topmost img element within a div with the class col-xs-4.");' + - text: Anida tu elemento h2 dentro de un div con la clase col-xs-8 . + testString: 'assert($("div.col-xs-8:has(h2)").length > 0 && $("div.col-xs-8:has(div)").length === 0, "Nest your h2 element within a div with the class col-xs-8.");' + - text: Asegúrese de que cada uno de sus elementos div tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    CatPhotoApp

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-bootstrap-wells.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-bootstrap-wells.spanish.md new file mode 100644 index 0000000000..2628a442db --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/create-bootstrap-wells.spanish.md @@ -0,0 +1,66 @@ +--- +id: bad87fee1348bd9aec908848 +title: Create Bootstrap Wells +localeTitle: Crear Bootstrap Wells +challengeType: 0 +--- + +## Description +
    +Bootstrap tiene una clase llamada well que puede crear un sentido visual de profundidad para sus columnas. +Nido uno div elemento con la clase well en cada uno de sus col-xs-6 div elementos. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Añadir un div elemento con la clase well dentro de cada uno de sus div elementos con la clase "col-xs-6" + testString: 'assert($("div.col-xs-6").not(":has(>div.well)").length < 1, "Add a div element with the class well inside each of your div elements with the class "col-xs-6"");' + - text: Anide ambos elementos div con la clase "col-xs-6" dentro de tu elemento div con la clase "row" . + testString: 'assert($("div.row > div.col-xs-6").length > 1, "Nest both of your div elements with the class "col-xs-6" within your div element with the class "row".");' + - text: Asegúrese de que todos los elementos div tengan etiquetas de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements have closing tags.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    + +
    +
    + +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/ditch-custom-css-for-bootstrap.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/ditch-custom-css-for-bootstrap.spanish.md new file mode 100644 index 0000000000..35c7de70d9 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/ditch-custom-css-for-bootstrap.spanish.md @@ -0,0 +1,130 @@ +--- +id: bad87fee1347bd9aedf08845 +title: Ditch Custom CSS for Bootstrap +localeTitle: Ditch Custom CSS para Bootstrap +challengeType: 0 +--- + +## Description +
    +Podemos limpiar nuestro código y hacer que nuestra aplicación Cat Photo se vea más convencional utilizando los estilos incorporados de Bootstrap en lugar de los estilos personalizados que creamos anteriormente. +No se preocupe, habrá mucho tiempo para personalizar nuestro CSS más adelante. +Elimine las declaraciones CSS de .red-text , p , y .smaller-image de su elemento de style para que las únicas declaraciones que queden en su elemento de style sean h2 y thick-green-border . +Luego borra el elemento p que contiene un enlace muerto. Luego elimine la clase de red-text de su elemento h2 y reemplácela con la clase Bootstrap text-primary . +Finalmente, elimine la clase de "imagen más pequeña" de su primer elemento img y reemplácela con la clase img-responsive . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Tu elemento h2 ya no debería tener la clase red-text . + testString: 'assert(!$("h2").hasClass("red-text"), "Your h2 element should no longer have the class red-text.");' + - text: Tu elemento h2 ahora debería tener la clase text-primary . + testString: 'assert($("h2").hasClass("text-primary"), "Your h2 element should now have the class text-primary.");' + - text: Tus elementos de párrafo ya no deberían usar la fuente Monospace . + testString: 'assert(!$("p").css("font-family").match(/monospace/i), "Your paragraph elements should no longer use the font Monospace.");' + - text: Elimine la clase de smaller-image de su imagen superior. + testString: 'assert(!$("img").hasClass("smaller-image"), "Remove the smaller-image class from your top image.");' + - text: Agregue la clase img-responsive a su imagen superior. + testString: 'assert($(".img-responsive").length > 1, "Add the img-responsive class to your top image.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/give-each-element-a-unique-id.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/give-each-element-a-unique-id.spanish.md new file mode 100644 index 0000000000..2cef655b05 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/give-each-element-a-unique-id.spanish.md @@ -0,0 +1,83 @@ +--- +id: bad87fee1348bd9aec908855 +title: Give Each Element a Unique id +localeTitle: Dale a cada elemento una identificación única +challengeType: 0 +--- + +## Description +
    +También desearemos poder usar jQuery para apuntar a cada botón por su ID única. +Dé a cada uno de sus botones una identificación única, comenzando con target1 y terminando con target6 . +Asegúrese de que target1 to target3 esté en #left-well , y target4 to target6 esté en #right-well . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Un elemento de button debe tener el id target1 . + testString: 'assert($("#left-well").children("#target1") && $("#left-well").children("#target1").length > 0, "One button element should have the id target1.");' + - text: Un elemento de button debe tener el id target2 . + testString: 'assert($("#left-well").children("#target2") && $("#left-well").children("#target2").length > 0, "One button element should have the id target2.");' + - text: Un elemento de button debe tener el id target3 . + testString: 'assert($("#left-well").children("#target3") && $("#left-well").children("#target3").length > 0, "One button element should have the id target3.");' + - text: Un elemento de button debe tener el id target4 . + testString: 'assert($("#right-well").children("#target4") && $("#right-well").children("#target4").length > 0, "One button element should have the id target4.");' + - text: Un elemento de button debe tener el id target5 . + testString: 'assert($("#right-well").children("#target5") && $("#right-well").children("#target5").length > 0, "One button element should have the id target5.");' + - text: Un elemento de button debe tener el id target6 . + testString: 'assert($("#right-well").children("#target6") && $("#right-well").children("#target6").length > 0, "One button element should have the id target6.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/house-our-page-within-a-bootstrap-container-fluid-div.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/house-our-page-within-a-bootstrap-container-fluid-div.spanish.md new file mode 100644 index 0000000000..ced4ec2b22 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/house-our-page-within-a-bootstrap-container-fluid-div.spanish.md @@ -0,0 +1,58 @@ +--- +id: bad87fee1348bd9aec908746 +title: House our page within a Bootstrap container-fluid div +localeTitle: Aloja nuestra página dentro de un div de fluido de contenedores Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora asegurémonos de que todo el contenido de su página responda a dispositivos móviles. +h3 su elemento h3 dentro de un elemento div con la clase container-fluid . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento div debe tener la clase container-fluid . + testString: 'assert($("div").hasClass("container-fluid"), "Your div element should have the class container-fluid.");' + - text: Asegúrese de que cada uno de sus elementos div tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements has a closing tag.");' + - text: Anida tu elemento h3 dentro de un elemento div . + testString: 'assert($("div").children("h3").length >0, "Nest your h3 element inside a div element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +

    jQuery Playground

    + + +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-buttons.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-buttons.spanish.md new file mode 100644 index 0000000000..93a19a9793 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-buttons.spanish.md @@ -0,0 +1,82 @@ +--- +id: bad87fee1348bd9aec908856 +title: Label Bootstrap Buttons +localeTitle: Botones de etiqueta Bootstrap +challengeType: 0 +--- + +## Description +
    +Al igual que etiquetamos nuestros pozos, queremos etiquetar nuestros botones. +Dé a cada uno de los elementos de su button texto que corresponda al selector de su id . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Déle a su elemento de button con el id target1 el texto #target1 '. + testString: 'assert(new RegExp("#target1","gi").test($("#target1").text()), "Give your button element with the id target1 the text #target1.");' + - text: 'Déle a su elemento de button con el id target2 el texto #target2 '. + testString: 'assert(new RegExp("#target2","gi").test($("#target2").text()), "Give your button element with the id target2 the text #target2.");' + - text: 'Déle a su elemento de button con el id target3 el texto #target3 '. + testString: 'assert(new RegExp("#target3","gi").test($("#target3").text()), "Give your button element with the id target3 the text #target3.");' + - text: 'Dale a tu elemento de button con el id target4 el texto #target4 '. + testString: 'assert(new RegExp("#target4","gi").test($("#target4").text()), "Give your button element with the id target4 the text #target4.");' + - text: 'Dale a tu elemento del button con el id target5 el texto #target5 '. + testString: 'assert(new RegExp("#target5","gi").test($("#target5").text()), "Give your button element with the id target5 the text #target5.");' + - text: 'Dale a tu elemento del button con el id target6 el texto #target6 '. + testString: 'assert(new RegExp("#target6","gi").test($("#target6").text()), "Give your button element with the id target6 the text #target6.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-wells.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-wells.spanish.md new file mode 100644 index 0000000000..493d26d0f0 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/label-bootstrap-wells.spanish.md @@ -0,0 +1,79 @@ +--- +id: bad87fee1348bd9aec908854 +title: Label Bootstrap Wells +localeTitle: Etiqueta Bootstrap Wells +challengeType: 0 +--- + +## Description +
    +Para mayor claridad, etiquetemos nuestros pozos con sus identificadores. +Por encima de su pozo izquierdo, dentro de su elemento div col-xs-6 , agregue un elemento h4 con el texto #left-well . +Por encima de su derecha-bien, dentro de su elemento div col-xs-6 , agregue un elemento h4 con el texto #right-well . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Agregue un elemento h4 a cada uno de sus elementos <div class="col-xs-6"> .' + testString: 'assert($(".col-xs-6").children("h4") && $(".col-xs-6").children("h4").length > 1, "Add an h4 element to each of your <div class="col-xs-6"> elements.");' + - text: 'Un elemento h4 debe tener el texto #left-well '. + testString: 'assert(new RegExp("#left-well","gi").test($("h4").text()), "One h4 element should have the text #left-well.");' + - text: 'Un elemento h4 debería tener el texto #right-well '. + testString: 'assert(new RegExp("#right-well","gi").test($("h4").text()), "One h4 element should have the text #right-well.");' + - text: Asegúrate de que todos tus elementos h4 tengan etiquetas de cierre. + testString: 'assert(code.match(/<\/h4>/g) && code.match(/

    /g).length === code.match(/

    h4 elements have closing tags.");' + +``` + +

    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    + +
    + + + +
    +
    +
    + +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/line-up-form-elements-responsively-with-bootstrap.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/line-up-form-elements-responsively-with-bootstrap.spanish.md new file mode 100644 index 0000000000..d34f5e353f --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/line-up-form-elements-responsively-with-bootstrap.spanish.md @@ -0,0 +1,133 @@ +--- +id: bad87fee1348bd9aec908845 +title: Line up Form Elements Responsively with Bootstrap +localeTitle: Alinee los elementos del formulario responsivamente con Bootstrap +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +Ahora obtengamos la input formulario y el button envío en la misma línea. Haremos esto de la misma manera que lo hemos hecho anteriormente: usando un elemento div con la row clase y otros elementos div dentro de ella usando la clase col-xs-* . +Anide tanto el input texto del formulario como el button envío dentro de un div con la row clase. Anide la input texto de tu formulario dentro de un div con la clase de col-xs-7 . Anide el button envío de su formulario en un div con la clase col-xs-5 . +Este es el último desafío que haremos por nuestra aplicación Cat Photo por ahora. ¡Esperamos que hayas disfrutado aprendiendo Font Awesome, Bootstrap y un diseño sensible! +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Anide el botón de envío de formulario y la entrada de texto en un div con row clase. + testString: 'assert($("div.row:has(input[type=\"text\"])").length > 0 && $("div.row:has(button[type=\"submit\"])").length > 0, "Nest your form submission button and text input in a div with class row.");' + - text: Anide la entrada de texto del formulario en un div con la clase col-xs-7 . + testString: 'assert($("div.col-xs-7:has(input[type=\"text\"])").length > 0, "Nest your form text input in a div with the class col-xs-7.");' + - text: Anide el botón de envío de formulario en un div con la clase col-xs-5 . + testString: 'assert($("div.col-xs-5:has(button[type=\"submit\"])").length > 0, "Nest your form submission button in a div with the class col-xs-5.");' + - text: Asegúrese de que cada uno de sus elementos div tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/make-images-mobile-responsive.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/make-images-mobile-responsive.spanish.md new file mode 100644 index 0000000000..647e3e5d56 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/make-images-mobile-responsive.spanish.md @@ -0,0 +1,116 @@ +--- +id: bad87fee1348bd9acde08812 +title: Make Images Mobile Responsive +localeTitle: Hacer móviles las imágenes receptivas +challengeType: 0 +--- + +## Description +
    +Primero, agregue una nueva imagen debajo de la existente. Establezca su atributo src en https://bit.ly/fcc-running-cats . +Sería genial si esta imagen pudiera tener exactamente el ancho de la pantalla de nuestro teléfono. +Afortunadamente, con Bootstrap, todo lo que necesitamos hacer es añadir la img-responsive clase a su imagen. Haga esto, y la imagen debe ajustarse perfectamente al ancho de su página. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Debes tener un total de dos imágenes. + testString: 'assert($("img").length === 2, "You should have a total of two images.");' + - text: Su nueva imagen debe estar debajo de la anterior y tener la clase img-responsive . + testString: 'assert($("img:eq(1)").hasClass("img-responsive"), "Your new image should be below your old one and have the class img-responsive.");' + - text: Su nueva imagen no debe tener la clase imagen más pequeña . + testString: 'assert(!$("img:eq(1)").hasClass("smaller-image"), "Your new image should not have the class smaller-image.");' + - text: 'Su nueva imagen debe tener un src de https & # 58; // bit.ly/fcc-running-cats .' + testString: 'assert($("img:eq(1)").attr("src") === "https://bit.ly/fcc-running-cats", "Your new image should have a src of https://bit.ly/fcc-running-cats.");' + - text: Asegúrese de que su nuevo elemento img tenga un soporte de ángulo de cierre. + testString: 'assert(code.match(//g).length === 2 && code.match(/img element has a closing angle bracket.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-checkboxes.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-checkboxes.spanish.md new file mode 100644 index 0000000000..cc505c2c40 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-checkboxes.spanish.md @@ -0,0 +1,122 @@ +--- +id: bad87fee1348bd9aeda08845 +title: Responsively Style Checkboxes +localeTitle: Casillas de verificación de estilo responsivo +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +También puede usar las clases col-xs-* en elementos de form ! De esta manera, nuestras casillas de verificación se distribuirán de manera uniforme en toda la página, independientemente de la resolución de la pantalla. +Anide las tres casillas de verificación en un elemento <div class="row"> . Luego anida cada uno de ellos en un elemento <div class="col-xs-4"> . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Anida todas las casillas de verificación dentro de un div con la row clase. + testString: 'assert($("div.row:has(input[type=\"checkbox\"])").length > 0, "Nest all of your checkboxes inside one div with the class row.");' + - text: Anida cada una de tus casillas dentro de su propia div con la clase col-xs-4 . + testString: 'assert($("div.col-xs-4:has(input[type=\"checkbox\"])").length > 2, "Nest each of your checkboxes inside its own div with the class col-xs-4.");' + - text: Asegúrese de que cada uno de sus elementos div tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    +
    +
    + +
    +
    + +
    +
    + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-radio-buttons.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-radio-buttons.spanish.md new file mode 100644 index 0000000000..9780600277 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/responsively-style-radio-buttons.spanish.md @@ -0,0 +1,116 @@ +--- +id: bad87fee1348bd9aedb08845 +title: Responsively Style Radio Buttons +localeTitle: Botones de radio de estilo responsivo +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +También puede usar las clases col-xs-* en elementos de form ! De esta manera, nuestros botones de radio se distribuirán de manera uniforme en toda la página, independientemente de la resolución de la pantalla. +Anide ambos botones de radio dentro de un elemento <div class="row"> . Luego anida cada uno de ellos dentro de un elemento <div class="col-xs-6"> . +Nota: Como recordatorio, los botones de radio son elementos de input del tipo de radio . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Anida todos los botones de radio dentro de un div con la row clase. + testString: 'assert($("div.row:has(input[type=\"radio\"])").length > 0, "Nest all of your radio buttons inside one div with the class row.");' + - text: Anida cada uno de sus botones de radio dentro de su propia div con la clase col-xs-6 . + testString: 'assert($("div.col-xs-6:has(input[type=\"radio\"])").length > 1, "Nest each of your radio buttons inside its own div with the class col-xs-6.");' + - text: Asegúrese de que cada uno de sus elementos div tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/split-your-bootstrap-row.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/split-your-bootstrap-row.spanish.md new file mode 100644 index 0000000000..30c53b16cd --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/split-your-bootstrap-row.spanish.md @@ -0,0 +1,60 @@ +--- +id: bad87fee1348bd9aec908847 +title: Split Your Bootstrap Row +localeTitle: Dividir tu fila Bootstrap +challengeType: 0 +--- + +## Description +
    +Ahora que tenemos una fila Bootstrap, dividámosla en dos columnas para albergar nuestros elementos. +Crea dos elementos div dentro de tu fila, ambos con la clase col-xs-6 . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Anide dos elementos div class="col-xs-6" dentro del elemento div class="row" . + testString: 'assert($("div.row > div.col-xs-6").length > 1, "Nest two div class="col-xs-6" elements within your div class="row" element.");' + - text: Asegúrese de que todos los elementos div tengan etiquetas de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div elements have closing tags.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/style-text-inputs-as-form-controls.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/style-text-inputs-as-form-controls.spanish.md new file mode 100644 index 0000000000..f1c8651a3f --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/style-text-inputs-as-form-controls.spanish.md @@ -0,0 +1,133 @@ +--- +id: bad87fee1348bd9aed908845 +title: Style Text Inputs as Form Controls +localeTitle: Entradas de texto de estilo como controles de formulario +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css' + raw: true +challengeType: 0 +--- + +## Description +
    +Puede agregar el ícono Font Awesome de fa-paper-plane agregando <i class="fa fa-paper-plane"></i> dentro del elemento del button envío. +Asigne al campo de entrada de texto de su formulario una clase de form-control de form-control . Déle a su formulario el botón de enviar las clases btn btn-primary . También dé a este botón el icono de Font Awesome de fa-paper-plane . +Todos los elementos textuales <input> , <textarea> y <select> con la clase .form-control tienen un ancho del 100%. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Dale al botón de enviar en tu formulario las clases btn btn-primary . + testString: 'assert($("button[type=\"submit\"]").hasClass("btn btn-primary"), "Give the submit button in your form the classes btn btn-primary.");' + - text: 'Agrega un <i class="fa fa-paper-plane"></i> dentro de tu elemento de button envío.' + testString: 'assert($("button[type=\"submit\"]:has(i.fa.fa-paper-plane)").length > 0, "Add a <i class="fa fa-paper-plane"></i> within your submit button element.");' + - text: Dale al texto input en tu formulario la clase form-control . + testString: 'assert($("input[type=\"text\"]").hasClass("form-control"), "Give the text input in your form the class form-control.");' + - text: Asegúrese de que cada uno de sus elementos i tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/i>/g) && code.match(/<\/i/g).length > 3, "Make sure each of your i elements has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +
    +
    +

    CatPhotoApp

    +
    +
    + A cute orange cat lying on its back. +
    +
    + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    +
    +
    + +
    +
    + +
    +
    +
    +
    + +
    +
    + +
    +
    + +
    +
    + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/taste-the-bootstrap-button-color-rainbow.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/taste-the-bootstrap-button-color-rainbow.spanish.md new file mode 100644 index 0000000000..78ca0c90ad --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/taste-the-bootstrap-button-color-rainbow.spanish.md @@ -0,0 +1,114 @@ +--- +id: bad87fee1348cd8acef08811 +title: Taste the Bootstrap Button Color Rainbow +localeTitle: Prueba el botín Bootstrap Color del arco iris +challengeType: 0 +--- + +## Description +
    +La clase btn-primary es el color principal que usarás en tu aplicación. Es útil para resaltar las acciones que desea que su usuario realice. +Reemplace la clase btn-default Bootstrap por btn-primary en su botón. +Tenga en cuenta que este botón todavía necesitará las clases btn y btn-block . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su botón debe tener la clase btn-primary . + testString: 'assert($("button").hasClass("btn-primary"), "Your button should have the class btn-primary.");' + - text: Tu botón aún debería tener las clases btn y btn-block . + testString: 'assert($("button").hasClass("btn-block") && $("button").hasClass("btn"), "Your button should still have the btn and btn-block classes.");' + - text: Asegúrese de que todos los elementos de sus button tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-a-span-to-target-inline-elements.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-a-span-to-target-inline-elements.spanish.md new file mode 100644 index 0000000000..3d63cd094d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-a-span-to-target-inline-elements.spanish.md @@ -0,0 +1,118 @@ +--- +id: bad87fee1348bd9aedf08845 +title: Use a span to Target Inline Elements +localeTitle: Use un lapso para apuntar elementos en línea +challengeType: 0 +--- + +## Description +
    +Puedes usar espacios para crear elementos en línea. ¿Recuerdas cuando usamos la clase btn-block para hacer que el botón llene toda la fila? + + +Que ilustra la diferencia entre un elemento "en línea" y un elemento de "bloque". +Al usar el elemento de span línea, puede colocar varios elementos en la misma línea, e incluso diseñar diferentes partes de la misma línea de manera diferente. +Anida la palabra "amor" en el elemento "Cosas que los gatos aman" debajo de un elemento de span . Luego, span la clase text-danger para hacer que el texto sea rojo. +continuación le indicamos cómo haría esto con el elemento "Las 3 principales cosas que los gatos odian": +<p>Top 3 things cats <span class="text-danger">hate:</span></p> +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento span debe estar dentro de su elemento p . + testString: 'assert($("p span") && $("p span").length > 0, "Your span element should be inside your p element.");' + - text: Tu elemento span debe tener solo el texto love . + testString: 'assert($("p span") && $("p span").text().match(/love/i) && !$("p span").text().match(/Things cats/i), "Your span element should have just the text love.");' + - text: Su elemento span debe tener clase de text-danger . + testString: 'assert($("span").hasClass("text-danger"), "Your span element should have class text-danger.");' + - text: Asegúrese de que su elemento span tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/span>/g) && code.match(//g).length === code.match(/span element has a closing tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. +
    +
    + +
    +
    + +
    +
    + +
    +
    +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-comments-to-clarify-code.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-comments-to-clarify-code.spanish.md new file mode 100644 index 0000000000..75b1173b81 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-comments-to-clarify-code.spanish.md @@ -0,0 +1,80 @@ +--- +id: bad87fee1348bd9aec908857 +title: Use Comments to Clarify Code +localeTitle: Utilizar comentarios para aclarar el código +challengeType: 0 +--- + +## Description +
    +Cuando comencemos a usar jQuery, modificaremos los elementos HTML sin necesidad de cambiarlos realmente en HTML. +Asegurémonos de que todos sepan que no deberían modificar nada de este código directamente. +Recuerde que puede comenzar un comentario con <!-- y terminar un comentario con --> +Agregue un comentario en la parte superior de su código HTML que diga Only change code above this line. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Comience un comentario con <!-- en la parte superior de su HTML'. + testString: 'assert(code.match(/^\s*.*this line))\s*.*this line.*\s*-->/gi), "Your comment should have the text Only change code above this line.");' + - text: 'Asegúrese de cerrar su comentario con --> .' + testString: 'assert(code.match(/-->.*\n+.+/g), "Be sure to close your comment with -->.");' + - text: Debes tener el mismo número de abridores y cerradores de comentarios. + testString: 'assert(code.match(//g).length, "You should have the same number of comment openers and closers.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers.spanish.md new file mode 100644 index 0000000000..fa7e92b0e3 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers.spanish.md @@ -0,0 +1,114 @@ +--- +id: bad87fee1348bd9acde08712 +title: Use Responsive Design with Bootstrap Fluid Containers +localeTitle: Utilice un diseño responsivo con los contenedores de líquidos Bootstrap +challengeType: 0 +--- + +## Description +
    +En la sección de HTML5 y CSS de freeCodeCamp construimos una aplicación Cat Photo. Ahora volvamos a ello. Esta vez, lo aplicaremos utilizando el popular marco de trabajo CSS que responde a Bootstrap. +Bootstrap descubrirá qué tan ancha es su pantalla y responderá redimensionando sus elementos HTML, de ahí el nombre Responsive Design . +Con un diseño responsivo, no es necesario diseñar una versión móvil de su sitio web. Se verá bien en dispositivos con pantallas de cualquier ancho. +Puede agregar Bootstrap a cualquier aplicación agregando el siguiente código en la parte superior de su HTML: +<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/> +En este caso, ya lo hemos agregado para esta página detrás de las escenas. Tenga en cuenta que es aceptable usar > o /> para cerrar la etiqueta de link . +Para comenzar, debemos anidar todo nuestro HTML (excepto la etiqueta de link y el elemento de style ) en un elemento div con la clase container-fluid . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento div debe tener la clase container-fluid . + testString: 'assert($("div").hasClass("container-fluid"), "Your div element should have the class container-fluid.");' + - text: Asegúrese de que su elemento div tiene una etiqueta de cierre. + testString: 'assert(code.match(/<\/div>/g) && code.match(/
    /g).length === code.match(/
    div element has a closing tag.");' + - text: Asegúrese de haber anidado todos los elementos HTML después de la etiqueta de style cierre en .container-fluid . + testString: 'assert($(".container-fluid").children().length >= 8, "Make sure you have nested all HTML elements after the closing style tag in .container-fluid.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + +

    CatPhotoApp

    + +

    Click here for cat photos.

    + +A cute orange cat lying on its back. + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-the-bootstrap-grid-to-put-elements-side-by-side.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-the-bootstrap-grid-to-put-elements-side-by-side.spanish.md new file mode 100644 index 0000000000..ec6aae3769 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/use-the-bootstrap-grid-to-put-elements-side-by-side.spanish.md @@ -0,0 +1,121 @@ +--- +id: bad88fee1348ce8acef08815 +title: Use the Bootstrap Grid to Put Elements Side By Side +localeTitle: Usa la rejilla de Bootstrap para poner los elementos lado a lado +challengeType: 0 +--- + +## Description +
    +Bootstrap utiliza un sistema de cuadrícula receptivo de 12 columnas, lo que facilita colocar los elementos en filas y especificar el ancho relativo de cada elemento. La mayoría de las clases de Bootstrap se pueden aplicar a un elemento div . +Bootstrap tiene diferentes atributos de ancho de columna que utiliza según la anchura de la pantalla del usuario. Por ejemplo, los teléfonos tienen pantallas estrechas y las computadoras portátiles tienen pantallas más anchas. +Tomemos, por ejemplo, la clase col-md-* . Aquí, md significa medio, y * es un número que especifica cuántas columnas de ancho debe tener el elemento. En este caso, se está especificando el ancho de columna de un elemento en una pantalla de tamaño mediano, como una computadora portátil. +En la aplicación Cat Photo que estamos construyendo, usaremos col-xs-* , donde xs significa extra pequeño (como una pantalla de teléfono móvil extra pequeño), y * es el número de columnas que especifican cuántas columnas de ancho El elemento debe ser. +Ponga los botones Like , Info y Delete lado a lado anidando los tres dentro de un elemento <div class="row"> , luego cada uno dentro de un <div class="col-xs-4"> elemento. +La clase de row se aplica a un div , y los propios botones se pueden anidar dentro de ella. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Todos sus botones deben estar anidados dentro del mismo elemento div con la row clase. + testString: 'assert($("div.row:has(button)").length > 0, "Your buttons should all be nested within the same div element with the class row.");' + - text: Cada uno de sus botones Bootstrap debe estar anidado dentro de su propio elemento div con la clase col-xs-4 . + testString: 'assert($("div.col-xs-4:has(button)").length > 2, "Each of your Bootstrap buttons should be nested within its own div element with the class col-xs-4.");' + - text: Asegúrese de que cada uno de los elementos de su button tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + + + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/warn-your-users-of-a-dangerous-action-with-btn-danger.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/warn-your-users-of-a-dangerous-action-with-btn-danger.spanish.md new file mode 100644 index 0000000000..205824fc62 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/bootstrap/warn-your-users-of-a-dangerous-action-with-btn-danger.spanish.md @@ -0,0 +1,117 @@ +--- +id: bad87fee1348ce8acef08814 +title: Warn Your Users of a Dangerous Action with btn-danger +localeTitle: Advierta a sus usuarios de una acción peligrosa con btn-danger +challengeType: 0 +--- + +## Description +
    +Bootstrap viene con varios colores predefinidos para botones. La clase btn-danger es el color del botón que usarás para notificar a los usuarios que el botón realiza una acción destructiva, como eliminar una foto de gato. +Crea un botón con el texto "Eliminar" y dale la clase btn-danger . +Tenga en cuenta que estos botones aún necesitan las clases btn y btn-block . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Crea un nuevo elemento de button con el texto "Eliminar". + testString: 'assert(new RegExp("Delete","gi").test($("button").text()), "Create a new button element with the text "Delete".");' + - text: Todos los botones de Bootstrap deben tener las clases btn y btn-block . + testString: 'assert($("button.btn-block.btn").length > 2, "All of your Bootstrap buttons should have the btn and btn-block classes.");' + - text: Tu nuevo botón debe tener la clase btn-danger . + testString: 'assert($("button").hasClass("btn-danger"), "Your new button should have the class btn-danger.");' + - text: Asegúrese de que todos los elementos de sus button tengan una etiqueta de cierre. + testString: 'assert(code.match(/<\/button>/g) && code.match(/
    + +## Challenge Seed +
    + +
    + +```html + + + +
    +

    CatPhotoApp

    + +

    Click here for cat photos.

    + + A cute orange cat lying on its back. + + Three kittens running towards the camera. + + +

    Things cats love:

    +
      +
    • cat nip
    • +
    • laser pointers
    • +
    • lasagna
    • +
    +

    Top 3 things cats hate:

    +
      +
    1. flea treatment
    2. +
    3. thunder
    4. +
    5. other cats
    6. +
    +
    + + + + + + + +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.spanish.md new file mode 100644 index 0000000000..fc7d878410 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-drum-machine.spanish.md @@ -0,0 +1,52 @@ +--- +id: 587d7dbc367417b2b2512bae +title: Build a Drum Machine +localeTitle: Construir una máquina de tambor +isRequired: true +challengeType: 3 +--- + +## Description +
    +Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/MJyNMd . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puede usar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debería usar un marco frontend (como React, por ejemplo) porque esta sección trata sobre el aprendizaje de marcos frontend. No se recomiendan las tecnologías adicionales no enumeradas anteriormente y su uso es bajo su propio riesgo. Estamos considerando la compatibilidad con otros marcos de frontend, como Angular y Vue, pero actualmente no se admiten. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Debería poder ver un contenedor externo con un id="drum-machine" que contiene todos los demás elementos. +Historia de usuario # 2: Dentro de #drum-machine puedo ver un elemento con una id="display" correspondiente id="display" . +Historia de usuario # 3: Dentro de #drum-machine puedo ver 9 elementos de pad de batería que se pueden hacer clic, cada uno con un nombre de clase de drum-pad , una identificación única que describe el clip de audio que la almohadilla de batería configurará para disparar, Texto interno que corresponde a una de las siguientes teclas del teclado: Q, W, E, A, S, D, Z, X, C. Los pads de batería DEBEN estar en este orden. +Historia de usuario # 4: Dentro de cada .drum-pad , debería haber un elemento de audio HTML5 que tenga un atributo src apunte a un clip de audio, un nombre de clase de clip y una identificación correspondiente al texto interno de su .drum-pad principal .drum-pad (por ejemplo, id="Q" , id="W" , id="E" etc.). +Historia de usuario n. ° 5: Cuando hago clic en un elemento .drum-pad , se debe activar el clip de audio contenido en su elemento de audio secundario. +Historia de usuario n. ° 6: Cuando .drum-pad la tecla de activación asociada con cada .drum-pad , el clip de audio contenido en su elemento de audio secundario debe activarse (por ejemplo, al presionar la tecla Q debe activar la batería que contiene la cadena "Q" , al presionar la tecla W se debe activar el pad de batería que contiene la cadena "W", etc.). +Historia de usuario # 7: cuando se .drum-pad un .drum-pad , una cadena que describe el clip de audio asociado se muestra como el texto interno del elemento #display (cada cadena debe ser única). +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: [] + +``` + +
    + +## Challenge Seed +
    + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.spanish.md new file mode 100644 index 0000000000..64a609abef --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-javascript-calculator.spanish.md @@ -0,0 +1,62 @@ +--- +id: bd7158d8c442eddfaeb5bd17 +title: Build a JavaScript Calculator +localeTitle: Construye una calculadora de JavaScript +challengeType: 3 +isRequired: true +--- + +## Description +
    +Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/wgGVVX . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puede usar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debería usar un marco frontend (como React, por ejemplo) porque esta sección trata sobre el aprendizaje de marcos frontend. No se recomiendan las tecnologías adicionales no enumeradas anteriormente y su uso es bajo su propio riesgo. Estamos considerando la compatibilidad con otros marcos de frontend, como Angular y Vue, pero actualmente no se admiten. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Mi calculadora debe contener un elemento pulsable que contenga un = (signo igual) con un id="equals" correspondiente id="equals" . +Historia de usuario # 2: Mi calculadora debe contener 10 elementos seleccionables que contengan un número cada uno de 0-9, con las siguientes ID correspondientes: id="zero" , id="one" , id="two" , id="three" , id="four" , id="five" , id="six" , id="seven" , id="eight" , e id="nine" . +Historia de usuario # 3: Mi calculadora debe contener 4 elementos seleccionables, cada uno de los cuales contiene uno de los 4 operadores matemáticos primarios con las siguientes ID correspondientes: id="add" , id="subtract" , id="multiply" , id="divide" . +Historia de usuario # 4: Mi calculadora debe contener un elemento pulsable que contenga a . Símbolo (punto decimal) con un id="decimal" correspondiente id="decimal" . +Historia de usuario n. ° 5: Mi calculadora debe contener un elemento seleccionable con un id="clear" . +Historia de usuario n. ° 6: Mi calculadora debe contener un elemento para mostrar los valores con una id="display" correspondiente id="display" . +Historia de usuario # 7: En cualquier momento, al presionar el botón de borrar se borran los valores de entrada y salida, y la calculadora vuelve a su estado inicializado; 0 debe mostrarse en el elemento con el id de display . +Historia de usuario n. ° 8: Al ingresar números, debería poder ver mi entrada en el elemento con la identificación de la display . +Historia de usuario n. ° 9: en cualquier orden, debería poder sumar, restar, multiplicar y dividir una cadena de números de cualquier longitud, y cuando presiono = , el resultado correcto debe mostrarse en el elemento con la identificación de la display . +Historia de usuario # 10: Al ingresar números, mi calculadora no debe permitir que un número comience con varios ceros. +Historia de usuario # 11: Cuando se hace clic en el elemento decimal, a . debe añadirse al valor mostrado actualmente; dos . en un número no debe ser aceptado. +Historia del usuario n. ° 12: debería poder realizar cualquier operación (+, -, *, /) en números que contengan puntos decimales. +Historia de usuario n. ° 13: Si se ingresan 2 o más operadores consecutivamente, la operación realizada debe ser la última que se ingresó. +Historia de usuario n. ° 14: Al presionar a un operador inmediatamente después de = debería comenzar un nuevo cálculo que opera sobre el resultado de la evaluación anterior. +Historia de usuario n. ° 15: Mi calculadora debe tener varios decimales de precisión cuando se trata de redondeo (tenga en cuenta que no hay un estándar exacto, pero debería poder manejar cálculos como 2 / 7 con una precisión razonable hasta al menos 4 decimales) ). +Nota sobre la lógica de la calculadora: se debe tener en cuenta que hay dos escuelas principales de pensamiento en la lógica de entrada de la calculadora: lógica de ejecución inmediata y lógica de fórmula . Nuestro ejemplo utiliza la fórmula lógica y observa el orden de prioridad de operación, la ejecución inmediata no. Cualquiera de los dos es aceptable, pero tenga en cuenta que dependiendo de lo que elija, su calculadora puede producir resultados diferentes a los nuestros para ciertas ecuaciones (vea el ejemplo a continuación). Siempre que sus cálculos puedan ser verificados por otra calculadora de producción, no considere esto como un error. +EJEMPLO: 3 + 5 x 6 - 2 / 4 =
    +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: [] + +``` + +
    + +## Challenge Seed +
    + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.spanish.md new file mode 100644 index 0000000000..030ace7c07 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-markdown-previewer.spanish.md @@ -0,0 +1,53 @@ +--- +id: bd7157d8c242eddfaeb5bd13 +title: Build a Markdown Previewer +localeTitle: Construir un previsualizador de rebajas +isRequired: true +challengeType: 3 +--- + +## Description +
    +Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/GrZVVO . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puede usar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debería usar un marco frontend (como React, por ejemplo) porque esta sección trata sobre el aprendizaje de marcos frontend. No se recomiendan las tecnologías adicionales no enumeradas anteriormente y su uso es bajo su propio riesgo. Estamos considerando la compatibilidad con otros marcos de frontend, como Angular y Vue, pero actualmente no se admiten. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario # 1: Puedo ver un elemento de área de textarea con un id="editor" . +Historia de usuario n. ° 2: puedo ver un elemento con un id="preview" correspondiente id="preview" . +Historia de usuario # 3: Cuando ingreso texto en el elemento #editor , el elemento #preview se actualiza a medida que #preview para mostrar el contenido del área de texto. +Historia de usuario n. ° 4: cuando ingreso la #editor GitHub en el elemento #editor , el texto se representa como HTML en el elemento #preview mientras #preview (SUGERENCIA: No necesita analizar Markdown usted mismo, puede importar el Marcado biblioteca para esto: https://cdnjs.com/libraries/marked ). +Historia de usuario # 5: Cuando mi previsualizador de markdown se carga por primera vez, el texto predeterminado en el campo #editor debe contener un markdown válido que represente al menos uno de cada uno de los siguientes elementos: un encabezado (tamaño H1), un encabezado secundario (tamaño H2) ), un enlace, un código en línea, un bloque de código, un elemento de la lista, una cita en bloque, una imagen y un texto en negrita. +Historia de usuario # 6: Cuando mi previsualizador de markdown se carga por primera vez, el markdown predeterminado en el campo #editor debe representarse como HTML en el elemento #preview . +Bonificación opcional (no es necesario que pase esta prueba): cuando hago clic en un enlace que aparece en mi vista previa de markdown, el enlace se abre en una nueva pestaña (SUGERENCIA: lea los documentos de Marked.js para esta). +Bonificación opcional (no es necesario que pase esta prueba): Mi previsualizador de reducción de marca interpreta los retornos de carro y los presenta como elementos br (salto de línea). +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: [] + +``` + +
    + +## Challenge Seed +
    + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-pomodoro-clock.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-pomodoro-clock.spanish.md new file mode 100644 index 0000000000..385cc5f60a --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-pomodoro-clock.spanish.md @@ -0,0 +1,73 @@ +--- +id: bd7158d8c442eddfaeb5bd0f +title: Build a Pomodoro Clock +localeTitle: Construir un reloj pomodoro +isRequired: true +challengeType: 3 +--- + +## Description +
    +Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/XpKrrW . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puede usar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debería usar un marco frontend (como React, por ejemplo) porque esta sección trata sobre el aprendizaje de marcos frontend. No se recomiendan las tecnologías adicionales no enumeradas anteriormente y su uso es bajo su propio riesgo. Estamos considerando la compatibilidad con otros marcos de frontend, como Angular y Vue, pero actualmente no se admiten. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario # 1: Puedo ver un elemento con id="break-label" que contiene una cadena (por ejemplo, "Break Length"). +Historia de usuario n. ° 2: Puedo ver un elemento con id="session-label" que contiene una cadena (por ejemplo, "Session Length"). +Historia de usuario n. ° 3: Puedo ver dos elementos seleccionables con las ID correspondientes: id="break-decrement" e id="session-decrement" . +Historia de usuario n. ° 4: Puedo ver dos elementos seleccionables con las identificaciones correspondientes: id="break-increment" e id="session-increment" . +Historia de usuario # 5: Puedo ver un elemento con una id="break-length" correspondiente id="break-length" , que por defecto (en carga) muestra un valor de 5. +Historia de usuario # 6: Puedo ver un elemento con una id="session-length" correspondiente id="session-length" , que por defecto muestra un valor de 25. +Historia de usuario # 7: Puedo ver un elemento con una id="timer-label" correspondiente id="timer-label" , que contiene una cadena que indica que una sesión está inicializada (por ejemplo, " Sesión"). +Historia de usuario n. ° 8: Puedo ver un elemento con el id="time-left" correspondiente id="time-left" . NOTA: En pausa o en ejecución, el valor en este campo siempre debe mostrarse en formato mm:ss (es decir, 25:00). +Historia de usuario # 9: Puedo ver un elemento id="start_stop" con una id="start_stop" correspondiente id="start_stop" . +Historia de usuario # 10: Puedo ver un elemento pulsable con una id="reset" correspondiente id="reset" . +Historia de usuario n. ° 11: Cuando hago clic en el elemento con el id de reset , se debe detener cualquier temporizador en ejecución, el valor dentro de id="break-length" debería volver a 5 , el valor dentro de id="session-length" debería vuelva a 25, y el elemento con id="time-left" debería restablecerse a su estado predeterminado. +Historia del usuario n. ° 12: Cuando hago clic en el elemento con el id de break-decrement , el valor dentro de id="break-length" reduce en un valor de 1, y puedo ver el valor actualizado. +Historia de usuario n. ° 13: Cuando hago clic en el elemento con el ID de break-increment de break-increment , el valor dentro de id="break-length" incrementa en un valor de 1, y puedo ver el valor actualizado. +Historia de usuario n. ° 14: Cuando hago clic en el elemento con el id de session-decrement de session-decrement , el valor dentro de id="session-length" reduce en un valor de 1, y puedo ver el valor actualizado. +Historia de usuario n. ° 15: Cuando hago clic en el elemento con el id de session-increment de session-increment , el valor dentro de id="session-length" incrementa en un valor de 1, y puedo ver el valor actualizado. +Historia de usuario n. ° 16: No debería poder establecer una sesión o duración de interrupción en <= 0. +Historia de usuario n. ° 17: No debería poder configurar una sesión o duración de interrupción en> 60. +Historia de usuario n. ° 18 : Cuando hago clic por primera vez en el elemento con id="start_stop" , el temporizador debería comenzar a ejecutarse desde el valor actualmente mostrado en id="session-length" , incluso si el valor se ha incrementado o disminuido desde el valor original de 25. +Historia de usuario n. ° 19: si el temporizador se está ejecutando, el elemento con el id del time-left debe mostrar el tiempo restante en formato mm:ss (disminuyendo en un valor de 1 y actualizando la pantalla cada 1000 ms). +Historia de usuario # 20: Si el temporizador se está ejecutando y hago clic en el elemento con id="start_stop" , la cuenta regresiva debe id="start_stop" . +Historia de usuario n. ° 21: si el temporizador está en pausa y hago clic en el elemento con id="start_stop" , la cuenta regresiva debería reanudarse desde el punto en el que se pausó. +Historia de usuario n. ° 22: cuando la cuenta regresiva de la sesión llega a cero (NOTA: el temporizador DEBE alcanzar las 00:00), y comienza una nueva cuenta regresiva, el elemento con la identificación de timer-label del timer-label debe mostrar una cadena que indica que ha comenzado una ruptura. +Historia de usuario # 23: cuando la cuenta regresiva de la sesión llega a cero (NOTA: el temporizador DEBE alcanzar las 00:00), debe comenzar una nueva cuenta regresiva de receso, contando desde el valor que se muestra actualmente en el elemento id="break-length" . +Historia de usuario n. ° 24: Cuando una cuenta regresiva de ruptura llega a cero (NOTA: el temporizador DEBE alcanzar las 00:00), y comienza una nueva cuenta regresiva, el elemento con la identificación de timer-label del timer-label debe mostrar una cadena que indica que la sesión ha comenzado. +Historia de usuario # 25: Cuando una cuenta regresiva de ruptura llega a cero (NOTA: el temporizador DEBE alcanzar las 00:00), debe comenzar una nueva cuenta regresiva de la sesión, contando desde el valor actualmente mostrado en el elemento id="session-length" . +Historia de usuario n. ° 26: cuando una cuenta regresiva llega a cero (NOTA: el temporizador DEBE alcanzar las 00:00), debe reproducirse un sonido que indique que el tiempo ha transcurrido. Esto debe utilizar una etiqueta de audio HTML5 y tener un id="beep" correspondiente id="beep" . +Historia de usuario # 27: El elemento de audio con id="beep" debe ser de 1 segundo o más. +Historia del usuario n. ° 28: el elemento de audio con el identificador de beep debe dejar de reproducirse y volver al principio cuando se hace clic en el elemento con el identificador de reset . +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: [] + +``` + +
    + +## Challenge Seed +
    + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.spanish.md new file mode 100644 index 0000000000..9dfa0b7321 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/front-end-libraries-projects/build-a-random-quote-machine.spanish.md @@ -0,0 +1,56 @@ +--- +id: bd7158d8c442eddfaeb5bd13 +title: Build a Random Quote Machine +localeTitle: Construir una máquina de cotización aleatoria +isRequired: true +challengeType: 3 +--- + +## Description +
    +Objetivo: crear una aplicación CodePen.io que sea funcionalmente similar a esta: https://codepen.io/freeCodeCamp/full/qRZeGZ . +Cumplir con las siguientes historias de usuario y obtener todas las pruebas para pasar. Dale tu propio estilo personal. +Puede usar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debería usar un marco frontend (como React, por ejemplo) porque esta sección trata sobre el aprendizaje de marcos frontend. No se recomiendan las tecnologías adicionales no enumeradas anteriormente y su uso es bajo su propio riesgo. Estamos considerando la compatibilidad con otros marcos de frontend, como Angular y Vue, pero actualmente no se admiten. Aceptaremos e intentaremos solucionar todos los informes de problemas que utilizan la pila de tecnología sugerida para este proyecto. ¡Feliz codificación! +Historia de usuario n. ° 1: Puedo ver un elemento de envoltorio con un id="quote-box" correspondiente id="quote-box" . +Historia de usuario # 2: Dentro de #quote-box , puedo ver un elemento con una id="text" correspondiente id="text" . +Historia de usuario # 3: Dentro de #quote-box , puedo ver un elemento con un id="author" correspondiente id="author" . +Historia de usuario # 4: Dentro de #quote-box , puedo ver un elemento seleccionable con un id="new-quote" correspondiente id="new-quote" . +Historia de usuario # 5: Dentro de #quote-box , puedo ver un clic elemento con un id="tweet-quote" correspondiente id="tweet-quote" . +Historia de usuario # 6: En la primera carga, mi máquina de cotizaciones muestra una cita aleatoria en el elemento con id="text" . +Historia de usuario # 7: En la primera carga, mi máquina de citas muestra el autor de la cita aleatoria en el elemento con id="author" . +Historia de usuario # 8: Cuando se hace clic en el botón #new-quote , mi máquina de cotizaciones debería buscar una nueva cita y mostrarla en el elemento #text . +Historia de usuario # 9: Mi máquina de cotizaciones debe buscar al autor de la nueva cotización cuando se hace clic en el botón #new-quote y mostrarla en el elemento #author . +Usuario Historia # 10: Puedo Tweet la cotización actual haciendo clic en el #tweet-quote a elemento. Este a elemento debe incluir la "twitter.com/intent/tweet" ruta de acceso en su href atributo a tweet la cotización actual. +Historia de usuario # 11: El elemento #quote-box wrapper debe estar centrado horizontalmente. Ejecute las pruebas con el nivel de zoom del navegador al 100% y la página maximizada. +Puede construir su proyecto por medio de este bolígrafo CodePen . O puede usar este enlace CDN para ejecutar las pruebas en cualquier entorno que desee: https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js +Una vez que haya terminado, envíe la URL a su Proyecto de trabajo con todas sus pruebas aprobadas. +Recuerda usar el método de lectura-búsqueda-pregunta si te atascas. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: [] + +``` + +
    + +## Challenge Seed +
    + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-text-inside-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-text-inside-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..3d5b4ac08d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-text-inside-an-element-using-jquery.spanish.md @@ -0,0 +1,95 @@ +--- +id: 564944c91be2204b269d51e3 +title: Change Text Inside an Element Using jQuery +localeTitle: Cambiar texto dentro de un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +Con jQuery, puede cambiar el texto entre las etiquetas de inicio y fin de un elemento. Incluso puedes cambiar el formato HTML. +jQuery tiene una función llamada .html() que le permite agregar etiquetas HTML y texto dentro de un elemento. Cualquier contenido previamente dentro del elemento será reemplazado completamente con el contenido que proporcione utilizando esta función. +Así es como reescribiría y enfatizaría el texto de nuestro encabezado: +$("h3").html("<em>jQuery Playground</em>"); +jQuery también tiene una función similar llamada .text() que solo altera el texto sin agregar etiquetas. En otras palabras, esta función no evaluará ninguna etiqueta HTML que se le pase, sino que la tratará como el texto con el que desea reemplazar el contenido existente. +Cambie el botón con id target4 enfatizando su texto. +Marque este enlace para saber más sobre la diferencia entre <i> y <em> y sus usos. +Tenga en cuenta que si bien la etiqueta <i> se ha usado tradicionalmente para enfatizar el texto, desde entonces se ha utilizado como etiqueta para los iconos. La etiqueta <em> ahora es ampliamente aceptada como la etiqueta de énfasis. Tampoco funcionará para este desafío. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: target4 el texto en su botón target4 agregando etiquetas HTML. + testString: 'assert.isTrue((/|\s*#target4\s*<\/em>|<\/i>/gi).test($("#target4").html()), "Emphasize the text in your target4 button by adding HTML tags.");' + - text: Asegúrate de que el texto no haya cambiado. + testString: 'assert($("#target4") && $("#target4").text().trim() === "#target4", "Make sure the text is otherwise unchanged.");' + - text: No alteres ningún otro texto. + testString: 'assert.isFalse((/|/gi).test($("h3").html()), "Do not alter any other text.");' + - text: Asegúrese de que está utilizando .html() y no .text() . + testString: 'assert(code.match(/\.html\(/g), "Make sure you are using .html() and not .text().");' + - text: Asegúrese de seleccionar button id="target4" con jQuery. + testString: 'assert(code.match(/\$\(\s*?(\"|\")#target4(\"|\")\s*?\)\.html\(/), "Make sure to select button id="target4" with jQuery.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-the-css-of-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-the-css-of-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..1e744a0659 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/change-the-css-of-an-element-using-jquery.spanish.md @@ -0,0 +1,93 @@ +--- +id: bad87fee1348bd9aed908826 +title: Change the CSS of an Element Using jQuery +localeTitle: Cambia el CSS de un elemento usando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +También podemos cambiar el CSS de un elemento HTML directamente con jQuery. +jQuery tiene una función llamada .css() que le permite cambiar el CSS de un elemento. +Así es como cambiaríamos su color a azul: +$("#target1").css("color", "blue"); +Esto es ligeramente diferente de una declaración CSS normal, porque la propiedad CSS y su valor están entre comillas y se separan con una coma en lugar de dos puntos. +Borre sus selectores jQuery, dejando una document ready function vacío document ready function . +Selecciona target1 y cambia su color a rojo. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento target1 debe tener texto rojo. + testString: 'assert($("#target1").css("color") === "rgb(255, 0, 0)", "Your target1 element should have red text.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/clone-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/clone-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..eea9f1a7da --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/clone-an-element-using-jquery.spanish.md @@ -0,0 +1,92 @@ +--- +id: bad87fee1348bd9aed508826 +title: Clone an Element Using jQuery +localeTitle: Clonar un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +Además de mover elementos, también puede copiarlos de un lugar a otro. +jQuery tiene una función llamada clone() que hace una copia de un elemento. +Por ejemplo, si quisiéramos copiar target2 de nuestro left-well a nuestro left-well right-well , $("#target2").clone().appendTo("#right-well"); : +$("#target2").clone().appendTo("#right-well"); +¿Notaste que esto involucra pegar dos funciones de jQuery? Esto se denomina function chaining y es una forma conveniente de hacer las cosas con jQuery. +Clone su elemento target5 y target5 a su left-well . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Tu elemento target5 debería estar dentro de tu right-well . + testString: 'assert($("#right-well").children("#target5").length > 0, "Your target5 element should be inside your right-well.");' + - text: Una copia de su elemento target5 también debe estar dentro de su left-well . + testString: 'assert($("#left-well").children("#target5").length > 0, "A copy of your target5 element should also be inside your left-well.");' + - text: Solo usa jQuery para mover estos elementos. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to move these elements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/delete-your-jquery-functions.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/delete-your-jquery-functions.spanish.md new file mode 100644 index 0000000000..a83a3b4d4b --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/delete-your-jquery-functions.spanish.md @@ -0,0 +1,110 @@ +--- +id: bad87fee1348bd9aeda08726 +title: Delete Your jQuery Functions +localeTitle: Borre sus funciones de jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +Estas animaciones fueron geniales al principio, pero ahora se están distrayendo. +Borre las tres funciones de jQuery de su función de document ready function , pero deje la document ready function intacta. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Elimine las tres funciones de jQuery de la función de document ready function . + testString: 'assert(code.match(/\{\s*\}\);/g), "Delete all three of your jQuery functions from your document ready function.");' + - text: Deja tu elemento de script intacto. + testString: 'assert(code.match(/ + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + + + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/disable-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/disable-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..bd3bbff66c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/disable-an-element-using-jquery.spanish.md @@ -0,0 +1,89 @@ +--- +id: bad87fee1348bd9aed808826 +title: Disable an Element Using jQuery +localeTitle: Deshabilitar un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +También puede cambiar las propiedades no CSS de elementos HTML con jQuery. Por ejemplo, puede deshabilitar botones. +Cuando desactiva un botón, se vuelve de color gris y ya no se puede hacer clic en él. +jQuery tiene una función llamada .prop() que le permite ajustar las propiedades de los elementos. +Así es como deshabilitaría todos los botones: +$("button").prop("disabled", true); +Deshabilita solo el botón target1 . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Desactiva tu botón target1 . + testString: 'assert($("#target1") && $("#target1").prop("disabled") && code.match(/[""]disabled[""],( true|true)/g), "Disable your target1 button.");' + - text: No deshabilite ningún otro botón. + testString: 'assert($("#target2") && !$("#target2").prop("disabled"), "Do not disable any other buttons.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(!code.match(/disabled[^<]*>/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/learn-how-script-tags-and-document-ready-work.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/learn-how-script-tags-and-document-ready-work.spanish.md new file mode 100644 index 0000000000..86bb4e36b7 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/learn-how-script-tags-and-document-ready-work.spanish.md @@ -0,0 +1,109 @@ +--- +id: bad87fee1348bd9acdd08826 +title: Learn How Script Tags and Document Ready Work +localeTitle: Aprenda cómo funcionan las etiquetas de script y el documento listo +challengeType: 6 +--- + +## Description +
    +Ahora estamos listos para aprender jQuery, la herramienta de JavaScript más popular de todos los tiempos. +Antes de que podamos comenzar a usar jQuery, necesitamos agregar algunas cosas a nuestro HTML. +Primero, agregue un elemento de script en la parte superior de su página. Asegúrate de cerrarla en la siguiente línea. +Su navegador ejecutará cualquier JavaScript dentro de un elemento de script , incluyendo jQuery. +Dentro de su elemento de script , agregue este código: $(document).ready(function() { a su script . Luego ciérrelo en la siguiente línea (aún dentro de su elemento de script ) con: }); +Aprenderemos más sobre las functions más adelante. Lo importante que debe saber es que el código que ingrese dentro de esta function se ejecutará tan pronto como su navegador haya cargado su página. +Esto es importante porque sin su document ready function , su código puede ejecutarse antes de que se genere su HTML, lo que causaría errores. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Cree un elemento de script asegurándose de que sea válido y tenga una etiqueta de cierre. + testString: 'assert(code.match(/<\/script\s*>/g) && code.match(//g) && code.match(/<\/script\s*>/g).length === code.match(//g).length, "Create a script element making sure it is valid and has a closing tag.");' + - text: 'Debes agregar $(document).ready (function() { al principio de tu elemento de script .' + testString: 'assert(code.match(/\$\s*?\(\s*?document\s*?\)\.ready\s*?\(\s*?function\s*?\(\s*?\)\s*?\{/g), "You should add
    + +```yml +tests: + - text: Create a script element making sure it is valid and has a closing tag. + testString: 'assert(code.match(/<\/script\s*>/g) && code.match(//g) && code.match(/<\/script\s*>/g).length === code.match(//g).length, "Create a script element making sure it is valid and has a closing tag.");' + - text: 'You should add $(document).ready(function() { to the beginning of your script element.' + testString: 'assert(code.match(/\$\s*?\(\s*?document\s*?\)\.ready\s*?\(\s*?function\s*?\(\s*?\)\s*?\{/g), "You should add $(document).ready(function() { to the beginning of your script element.");' + - text: 'Close your $(document).ready(function() { function with });' + testString: 'assert(code.match(/\n*?\s*?\}\s*?\);/g), "Close your $(document).ready(function() { function with });");' + +``` + +
    #40;document).ready(function() {
    to the beginning of your script element.");' + - text: 'Cierre su $(document).ready (function() { function with }); ' + testString: 'assert(code.match(/\n*?\s*?\}\s*?\);/g), "Close your
    + +```yml +tests: + - text: Create a script element making sure it is valid and has a closing tag. + testString: 'assert(code.match(/<\/script\s*>/g) && code.match(//g) && code.match(/<\/script\s*>/g).length === code.match(//g).length, "Create a script element making sure it is valid and has a closing tag.");' + - text: 'You should add $(document).ready(function() { to the beginning of your script element.' + testString: 'assert(code.match(/\$\s*?\(\s*?document\s*?\)\.ready\s*?\(\s*?function\s*?\(\s*?\)\s*?\{/g), "You should add $(document).ready(function() { to the beginning of your script element.");' + - text: 'Close your $(document).ready(function() { function with });' + testString: 'assert(code.match(/\n*?\s*?\}\s*?\);/g), "Close your $(document).ready(function() { function with });");' + +``` + +
    #40;document).ready(function() {
    function with });");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..70ae0b6c20 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-an-element-using-jquery.spanish.md @@ -0,0 +1,85 @@ +--- +id: bad87fee1348bd9aed708826 +title: Remove an Element Using jQuery +localeTitle: Eliminar un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +Ahora, eliminemos un elemento HTML de su página usando jQuery. +jQuery tiene una función llamada .remove() que eliminará por completo un elemento HTML +Eliminar el elemento target4 de la página usando la función .remove() . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Usa jQuery para eliminar tu elemento target4 de tu página. + testString: 'assert($("#target4").length === 0 && code.match(/\$\([""]#target4[""]\).remove\(\)/g), "Use jQuery to remove your target4 element from your page.");' + - text: Solo usa jQuery para eliminar este elemento. + testString: 'assert(code.match(/id="target4/g) && !code.match(//g) && $("#right-well").length > 0, "Only use jQuery to remove this element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-classes-from-an-element-with-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-classes-from-an-element-with-jquery.spanish.md new file mode 100644 index 0000000000..bcb170e480 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/remove-classes-from-an-element-with-jquery.spanish.md @@ -0,0 +1,91 @@ +--- +id: bad87fee1348bd9aed918626 +title: Remove Classes from an Element with jQuery +localeTitle: Eliminar clases de un elemento con jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +De la misma manera que puede agregar clases a un elemento con la función addClass() jQuery, puede eliminarlas con la función removeClass() jQuery. +Así es como haría esto para un botón específico: +$("#target2").removeClass("btn-default"); +btn-default clase btn-default de todos nuestros elementos de button . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Elimine la clase btn-default de todos sus elementos de button . + testString: 'assert($(".btn-default").length === 0, "Remove the btn-default class from all of your button elements.");' + - text: Utilice solo jQuery para eliminar esta clase del elemento. + testString: 'assert(code.match(/btn btn-default/g), "Only use jQuery to remove this class from the element.");' + - text: Sólo elimine la clase btn-default . + testString: 'assert(code.match(/\.[\v\s]*removeClass[\s\v]*\([\s\v]*("|")\s*btn-default\s*("|")[\s\v]*\)/gm), "Only remove the btn-default class.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-a-specific-child-of-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-a-specific-child-of-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..6e7a036424 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-a-specific-child-of-an-element-using-jquery.spanish.md @@ -0,0 +1,99 @@ +--- +id: bad87fee1348bd9aed108826 +title: Target a Specific Child of an Element Using jQuery +localeTitle: Apunta a un niño específico de un elemento usando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +Ha visto por qué los atributos de identificación son tan convenientes para la selección de objetivos con los selectores jQuery. Pero no siempre tendrás tan buenos identificadores con los que trabajar. +Afortunadamente, jQuery tiene algunos otros trucos para apuntar a los elementos correctos. +jQuery usa los selectores de CSS para apuntar a los elementos. El selector de CSS target:nth-child(n) permite seleccionar todos los elementos nth con la clase de destino o el tipo de elemento. +Así es como le darías al tercer elemento en cada pozo la clase de rebote: +$(".target:nth-child(3)").addClass("animated bounce"); +Haz que el segundo niño en cada uno de tus elementos de pozo rebote. Debes seleccionar los elementos de los hijos con la clase target . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: El segundo elemento en sus elementos target debe rebotar. + testString: 'assert($(".target:nth-child(2)").hasClass("animated") && $(".target:nth-child(2)").hasClass("bounce"), "The second element in your target elements should bounce.");' + - text: Solo dos elementos deben rebotar. + testString: 'assert($(".animated.bounce").length === 2, "Only two elements should bounce.");' + - text: 'Debería usar el selector :nth-child() para modificar estos elementos.' + testString: 'assert(code.match(/\:nth-child\(/g), "You should use the :nth-child() selector to modify these elements.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(code.match(/\$\(".target:nth-child\(2\)"\)/g) || code.match(/\$\(".target:nth-child\(2\)"\)/g) || code.match(/\$\(".target"\).filter\(":nth-child\(2\)"\)/g) || code.match(/\$\(".target"\).filter\(":nth-child\(2\)"\)/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-class-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-class-using-jquery.spanish.md new file mode 100644 index 0000000000..dda381c54e --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-class-using-jquery.spanish.md @@ -0,0 +1,89 @@ +--- +id: bad87fee1348bd9aedc08826 +title: Target Elements by Class Using jQuery +localeTitle: Elementos de destino por clase usando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +¿Ves cómo hicimos rebotar todos los elementos de tus button ? Los seleccionamos con $("button") , luego les agregamos algunas clases de CSS con .addClass("animated bounce"); . +Acaba de usar la función .addClass() jQuery, que le permite agregar clases a los elementos. +En primer lugar, vamos a orientar su div elementos con la clase well mediante el uso de la $(".well") selector. +Tenga en cuenta que, al igual que con las declaraciones de CSS, escribe a . antes del nombre de la clase. +Luego usa la función .addClass() jQuery para agregar las clases animated y shake . +Por ejemplo, puede hacer que todos los elementos con la clase text-primary shake agregando lo siguiente a su document ready function : +$(".text-primary").addClass("animated shake"); +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Use el jQuery addClass() la función de dar las clases animated y shake a todos sus elementos con la clase well .' + testString: 'assert($(".well").hasClass("animated") && $(".well").hasClass("shake"), "Use the jQuery addClass() function to give the classes animated and shake to all your elements with the class well.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(!code.match(/class\.\*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-id-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-id-using-jquery.spanish.md new file mode 100644 index 0000000000..69e92a4a67 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-elements-by-id-using-jquery.spanish.md @@ -0,0 +1,92 @@ +--- +id: bad87fee1348bd9aeda08826 +title: Target Elements by id Using jQuery +localeTitle: Elementos de destino por id usando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +También puede apuntar elementos por sus atributos de identificación. +Primero apunte el elemento de su button con el id target3 usando el selector $("#target3") . +Tenga en cuenta que, al igual que con las declaraciones de CSS, escribe un # antes del nombre del ID. +Luego use la función .addClass() jQuery para agregar las clases animated y fadeOut . +Así es como harías que el elemento del button con el id target6 desvanezca: +$("#target6").addClass("animated fadeOut") . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Seleccione el elemento del button con el id de target3 y use la función jQuery addClass() para darle la clase de animated .' + testString: 'assert($("#target3").hasClass("animated"), "Select the button element with the id of target3 and use the jQuery addClass() function to give it the class of animated.");' + - text: ' target3 al elemento con el id target3 y usa la función jQuery addClass() para darle a la clase fadeOut .' + testString: 'assert(($("#target3").hasClass("fadeOut") || $("#target3").hasClass("fadeout")) && code.match(/\$\(\s*.#target3.\s*\)/g), "Target the element with the id target3 and use the jQuery addClass() function to give it the class fadeOut.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-even-elements-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-even-elements-using-jquery.spanish.md new file mode 100644 index 0000000000..402fdc8c49 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-even-elements-using-jquery.spanish.md @@ -0,0 +1,98 @@ +--- +id: bad87fee1348bd9aed008826 +title: Target Even Elements Using jQuery +localeTitle: Destinar los elementos pares usando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +También puede apuntar elementos según sus posiciones usando :odd o :even selectores :even . +Tenga en cuenta que jQuery tiene un índice de cero, lo que significa que el primer elemento de una selección tiene una posición de 0. Esto puede ser un poco confuso, ya que, en contra de la intuición,: :odd selecciona el segundo elemento (posición 1), cuarto elemento (posición 3). ), y así. +Así es como se enfocaría en todos los elementos impares con la clase target y les daría clases: +$(".target:odd").addClass("animated shake"); +Intenta seleccionar todos los elementos target uniformes y dales las clases de animated y shake . Recuerde que incluso se refiere a la posición de los elementos con un sistema basado en cero en mente. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Todos los elementos de target que jQuery considera que están parejos deben sacudirse. + testString: 'assert($(".target:even").hasClass("animated") && $(".target:even").hasClass("shake"), "All of the target elements that jQuery considers to be even should shake.");' + - text: 'Deberías usar el selector :even para modificar estos elementos'. + testString: 'assert(code.match(/\:even/g), "You should use the :even selector to modify these elements.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(code.match(/\$\(".target:even"\)/g) || code.match(/\$\(".target:even"\)/g) || code.match(/\$\(".target"\).filter\(":even"\)/g) || code.match(/\$\(".target"\).filter\(":even"\)/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-html-elements-with-selectors-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-html-elements-with-selectors-using-jquery.spanish.md new file mode 100644 index 0000000000..acf2c6a2cb --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-html-elements-with-selectors-using-jquery.spanish.md @@ -0,0 +1,90 @@ +--- +id: bad87fee1348bd9bedc08826 +title: Target HTML Elements with Selectors Using jQuery +localeTitle: Destinar elementos HTML con selectores utilizando jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +Ahora tenemos una document ready function . +Ahora vamos a escribir nuestra primera declaración jQuery. Todas las funciones de jQuery comienzan con un $ , generalmente conocido como dollar sign operator , o como bling . +jQuery a menudo selecciona un elemento HTML con un selector , luego le hace algo a ese elemento. +Por ejemplo, hagamos que todos los elementos de tus button reboten. Solo agregue este código dentro de su función de documento listo: +$("button").addClass("animated bounce"); +Tenga en cuenta que ya hemos incluido la biblioteca jQuery y la biblioteca Animate.css en segundo plano para que pueda usarlas en el editor. Así que estás utilizando jQuery para aplicar la clase de bounce Animate.css a los elementos de tu button . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Use el jQuery addClass() la función de dar las clases animated y bounce a sus button elementos.' + testString: 'assert($("button").hasClass("animated") && $("button").hasClass("bounce"), "Use the jQuery addClass() function to give the classes animated and bounce to your button elements.");' + - text: Solo use jQuery para agregar estos colores al elemento. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these colors to the element.");' + - text: Su código jQuery debe estar dentro de $(document).ready(); función. + testString: 'assert(code.match(/\$\(document\)\.ready\(function.*(\s|\n)*.*button.*.addClass.*\);/g), "Your jQuery code should be within the $(document).ready(); function.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-children-of-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-children-of-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..e9d8ab6df9 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-children-of-an-element-using-jquery.spanish.md @@ -0,0 +1,92 @@ +--- +id: bad87fee1348bd9aed208826 +title: Target the Children of an Element Using jQuery +localeTitle: Apunta a los hijos de un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +Cuando los elementos HTML se colocan un nivel debajo de otro, se denominan children de ese elemento. Por ejemplo, los elementos de los botones en este desafío con el texto "# destino1", "# destino2", y "# destino3" son todos children de la <div class="well" id="left-well"> elemento. +jQuery tiene una función llamada children() que le permite acceder a los hijos de cualquier elemento que haya seleccionado. +Este es un ejemplo de cómo usaría la función children() para dar a los niños de su elemento de left-well el color blue : +$("#left-well").children().css("color", "blue") +
    + +## Instructions +
    +Dale a todos los niños de tu elemento de right-well el color naranja. +
    + +## Tests +
    + +```yml +tests: + - text: 'Todos los niños de #right-well deben tener texto naranja'. + testString: 'assert($("#right-well").children().css("color") === "rgb(255, 165, 0)", "All children of #right-well should have orange text.");' + - text: 'Deberías usar la función children() para modificar estos elementos.' + testString: 'assert(code.match(/\.children\(\)\.css/g), "You should use the children() function to modify these elements.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(code.match(/
    /g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-parent-of-an-element-using-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-parent-of-an-element-using-jquery.spanish.md new file mode 100644 index 0000000000..55b29b2a1c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-parent-of-an-element-using-jquery.spanish.md @@ -0,0 +1,97 @@ +--- +id: bad87fee1348bd9aed308826 +title: Target the Parent of an Element Using jQuery +localeTitle: Apunta al padre de un elemento usando jQuery +challengeType: 6 +--- + +## Description +
    +Cada elemento HTML tiene un elemento parent del cual inherits propiedades. +Por ejemplo, su elemento jQuery Playground h3 tiene el elemento primario de <div class="container-fluid"> , que a su vez tiene el body principal. +jQuery tiene una función llamada parent() que le permite acceder al padre de cualquier elemento que haya seleccionado. +Este es un ejemplo de cómo usaría la función parent() si quisiera darle al elemento padre del elemento del left-well un color de fondo azul: +$("#left-well").parent().css("background-color", "blue") +#target1 al padre del elemento #target1 un color de fondo rojo. +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Su elemento de left-well debe tener un fondo rojo. + testString: 'assert($("#left-well").css("background-color") === "red" || $("#left-well").css("background-color") === "rgb(255, 0, 0)" || $("#left-well").css("background-color").toLowerCase() === "#ff0000" || $("#left-well").css("background-color").toLowerCase() === "#f00", "Your left-well element should have a red background.");' + - text: 'Deberías usar la función .parent() para modificar este elemento.' + testString: 'assert(code.match(/\.parent\s*\(\s*\)\s*\.css/g), "You should use the .parent() function to modify this element.");' + - text: 'El método .parent() debe llamarse en el elemento #target1 .' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?#target1\s*?(?:"|")\s*?\)\s*?\.parent/gi), "The .parent() method should be called on the #target1 element.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(code.match(/
    /g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    + +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-same-element-with-multiple-jquery-selectors.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-same-element-with-multiple-jquery-selectors.spanish.md new file mode 100644 index 0000000000..34d050747f --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/target-the-same-element-with-multiple-jquery-selectors.spanish.md @@ -0,0 +1,154 @@ +--- +id: bad87fee1348bd9aed908626 +title: Target the Same Element with Multiple jQuery Selectors +localeTitle: Apunta el mismo elemento con múltiples selectores jQuery +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +Ahora conoce tres formas de apuntar elementos: por tipo: $("button") , por clase: $(".btn") , y por id $("#target1") . +Aunque es posible agregar varias clases en una sola llamada .addClass() , las agregaremos al mismo elemento de tres maneras diferentes . +Usando .addClass() , agregue solo una clase a la vez al mismo elemento, de tres maneras diferentes: +Agregue la clase animated a todos los elementos con el button tipo. +Agregue la clase shake a todos los botones con la clase .btn . +Agregue la clase btn-primary al botón con id #target1 . +Nota
    Solo debes apuntar a un elemento y agregar solo una clase a la vez. En total, sus tres selectores individuales terminarán agregando las tres clases shake , animated y btn-primary a #target1 . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: 'Use el selector $("button") .' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?button\s*?(?:"|")/gi), "Use the
    + +```yml +tests: + - text: 'Use the $("button") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?button\s*?(?:"|")/gi), "Use the $("button") selector.");' + - text: 'Use the $(".btn") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?\.btn\s*?(?:"|")/gi), "Use the $(".btn") selector.");' + - text: 'Use the $("#target1") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?#target1\s*?(?:"|")/gi), "Use the $("#target1") selector.");' + - text: Only add one class with each of your three selectors. + testString: 'assert(code.match(/addClass/g) && code.match(/addClass\s*?\(\s*?("|")\s*?[\w-]+\s*?\1\s*?\)/g).length > 2, "Only add one class with each of your three selectors.");' + - text: 'Your #target1 element should have the classes animatedshake and btn-primary.' + testString: 'assert($("#target1").hasClass("animated") && $("#target1").hasClass("shake") && $("#target1").hasClass("btn-primary"), "Your #target1 element should have the classes animatedshake and btn-primary.");' + - text: Only use jQuery to add these classes to the element. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    #40"button")
    selector.");' + - text: 'Use el selector $(".btn") .' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?\.btn\s*?(?:"|")/gi), "Use the
    + +```yml +tests: + - text: 'Use the $("button") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?button\s*?(?:"|")/gi), "Use the $("button") selector.");' + - text: 'Use the $(".btn") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?\.btn\s*?(?:"|")/gi), "Use the $(".btn") selector.");' + - text: 'Use the $("#target1") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?#target1\s*?(?:"|")/gi), "Use the $("#target1") selector.");' + - text: Only add one class with each of your three selectors. + testString: 'assert(code.match(/addClass/g) && code.match(/addClass\s*?\(\s*?("|")\s*?[\w-]+\s*?\1\s*?\)/g).length > 2, "Only add one class with each of your three selectors.");' + - text: 'Your #target1 element should have the classes animatedshake and btn-primary.' + testString: 'assert($("#target1").hasClass("animated") && $("#target1").hasClass("shake") && $("#target1").hasClass("btn-primary"), "Your #target1 element should have the classes animatedshake and btn-primary.");' + - text: Only use jQuery to add these classes to the element. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    #40".btn")
    selector.");' + - text: 'Use el selector $("#target1") .' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?#target1\s*?(?:"|")/gi), "Use the
    + +```yml +tests: + - text: 'Use the $("button") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?button\s*?(?:"|")/gi), "Use the $("button") selector.");' + - text: 'Use the $(".btn") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?\.btn\s*?(?:"|")/gi), "Use the $(".btn") selector.");' + - text: 'Use the $("#target1") selector.' + testString: 'assert(code.match(/\$\s*?\(\s*?(?:"|")\s*?#target1\s*?(?:"|")/gi), "Use the $("#target1") selector.");' + - text: Only add one class with each of your three selectors. + testString: 'assert(code.match(/addClass/g) && code.match(/addClass\s*?\(\s*?("|")\s*?[\w-]+\s*?\1\s*?\)/g).length > 2, "Only add one class with each of your three selectors.");' + - text: 'Your #target1 element should have the classes animatedshake and btn-primary.' + testString: 'assert($("#target1").hasClass("animated") && $("#target1").hasClass("shake") && $("#target1").hasClass("btn-primary"), "Your #target1 element should have the classes animatedshake and btn-primary.");' + - text: Only use jQuery to add these classes to the element. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    #40"#target1")
    selector.");' + - text: Solo agrega una clase con cada uno de tus tres selectores. + testString: 'assert(code.match(/addClass/g) && code.match(/addClass\s*?\(\s*?("|")\s*?[\w-]+\s*?\1\s*?\)/g).length > 2, "Only add one class with each of your three selectors.");' + - text: 'Su elemento #target1 debería tener las clases animated , shake y btn-primary '. + testString: 'assert($("#target1").hasClass("animated") && $("#target1").hasClass("shake") && $("#target1").hasClass("btn-primary"), "Your #target1 element should have the classes animatedshake and btn-primary.");' + - text: Solo use jQuery para agregar estas clases al elemento. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to add these classes to the element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-appendto-to-move-elements-with-jquery.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-appendto-to-move-elements-with-jquery.spanish.md new file mode 100644 index 0000000000..2059627345 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-appendto-to-move-elements-with-jquery.spanish.md @@ -0,0 +1,90 @@ +--- +id: bad87fee1348bd9aed608826 +title: Use appendTo to Move Elements with jQuery +localeTitle: Usa appendTo para mover elementos con jQuery +challengeType: 6 +--- + +## Description +
    +Ahora intentemos mover elementos de un div a otro. +jQuery tiene una función llamada appendTo() que le permite seleccionar elementos HTML y agregarlos a otro elemento. +Por ejemplo, si quisiéramos mover target4 de nuestro pozo derecho a nuestro pozo izquierdo, $("#target4").appendTo("#left-well"); : +$("#target4").appendTo("#left-well"); +Mueva su elemento target2 de su left-well a su right-well . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Tu elemento target2 no debe estar dentro de tu left-well . + testString: 'assert($("#left-well").children("#target2").length === 0, "Your target2 element should not be inside your left-well.");' + - text: Tu elemento target2 debe estar dentro de tu right-well . + testString: 'assert($("#right-well").children("#target2").length > 0, "Your target2 element should be inside your right-well.");' + - text: Solo usa jQuery para mover estos elementos. + testString: 'assert(!code.match(/class.*animated/g), "Only use jQuery to move these elements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-jquery-to-modify-the-entire-page.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-jquery-to-modify-the-entire-page.spanish.md new file mode 100644 index 0000000000..840c311bb6 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/jquery/use-jquery-to-modify-the-entire-page.spanish.md @@ -0,0 +1,94 @@ +--- +id: bad87fee1348bd9aecb08826 +title: Use jQuery to Modify the Entire Page +localeTitle: Usa jQuery para modificar la página completa +required: + - link: 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.0/animate.css' +challengeType: 6 +--- + +## Description +
    +Hemos terminado de jugar con nuestro patio de juegos jQuery. ¡Vamos a derribarlo! +jQuery también puede apuntar al elemento del body . +Así es como haríamos que todo el cuerpo se desvanezca: $("body").addClass("animated fadeOut"); +Pero hagamos algo más dramático. Agrega las clases animated y hinge a tu body . +
    + +## Instructions +
    + +
    + +## Tests +
    + +```yml +tests: + - text: Agrega las clases animated y hinge a tu body . + testString: 'assert($("body").hasClass("animated") && $("body").hasClass("hinge"), "Add the classes animated and hinge to your body element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```html + + + + +
    +

    jQuery Playground

    +
    +
    +

    #left-well

    +
    + + + +
    +
    +
    +

    #right-well

    +
    + + + +
    +
    +
    +
    +``` + +
    + + + +
    + +## Solution +
    + +```js +// solution required +``` +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-react.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-react.spanish.md new file mode 100644 index 0000000000..5756fd21eb --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-react.spanish.md @@ -0,0 +1,135 @@ +--- +id: 5a24c314108439a4d4036147 +title: Connect Redux to React +localeTitle: Conecta Redux a Reaccionar +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ahora que ha escrito las mapStateToProps() y mapDispatchToProps() , puede usarlas para mapear el state y dispatch a las props de uno de sus componentes React. El método de connect de React Redux puede manejar esta tarea. Este método toma dos argumentos opcionales, mapStateToProps() y mapDispatchToProps() . Son opcionales porque puede tener un componente que solo necesita acceso al state pero no necesita enviar ninguna acción, o viceversa. +Para usar este método, pase las funciones como argumentos e inmediatamente llame al resultado con su componente. Esta sintaxis es un poco inusual y se parece a: +connect(mapStateToProps, mapDispatchToProps)(MyComponent) +Nota: Si desea omitir uno de los argumentos del método connect , pasa null en su lugar. +
    + +## Instructions +
    +El editor de código tiene las mapStateToProps() y mapDispatchToProps() y un nuevo componente React llamado Presentational . Conecte este componente para Redux con la connect método de la ReactRedux objeto global, y lo llaman inmediatamente en el Presentational componente. Asigne el resultado a una nueva const llamada ConnectedComponent que representa el componente conectado. Eso es todo, ahora estás conectado a Redux! Intente cambiar cualquiera de los argumentos de connect a null y observe los resultados de la prueba. +
    + +## Tests +
    + +```yml +tests: + - text: El componente de Presentational debe hacer. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("Presentational").length === 1; })(), "The Presentational component should render.");' + - text: El componente de Presentational debe recibir messages prop messages través de connect . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return props.messages === "__INITIAL__STATE__"; })(), "The Presentational component should receive a prop messages via connect.");' + - text: El componente de Presentational debe recibir un prop submitNewMessage través de connect . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const props = mockedComponent.find("Presentational").props(); return typeof props.submitNewMessage === "function"; })(), "The Presentational component should receive a prop submitNewMessage via connect.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const addMessage = (message) => { + return { + type: 'ADD', + message: message + } +}; + +const mapStateToProps = (state) => { + return { + messages: state + } +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (message) => { + dispatch(addMessage(message)); + } + } +}; + +class Presentational extends React.Component { + constructor(props) { + super(props); + } + render() { + return

    This is a Presentational Component

    + } +}; + +const connect = ReactRedux.connect; +// change code below this line + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const addMessage = (message) => { + return { + type: 'ADD', + message: message + } +}; + +const mapStateToProps = (state) => { + return { + messages: state + } +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (message) => { + dispatch(addMessage(message)); + } + } +}; + +class Presentational extends React.Component { + constructor(props) { + super(props); + } + render() { + return

    This is a Presentational Component

    + } +}; + +const connect = ReactRedux.connect; +// change code below this line + +const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps)(Presentational); + +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.spanish.md new file mode 100644 index 0000000000..e3a48305bb --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/connect-redux-to-the-messages-app.spanish.md @@ -0,0 +1,265 @@ +--- +id: 5a24c314108439a4d4036148 +title: Connect Redux to the Messages App +localeTitle: Connect Redux a la aplicación de mensajes +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ahora que entiende cómo usar connect para conectarse React to Redux, puede aplicar lo que ha aprendido a su componente React que maneja los mensajes. +En la última lección, el componente que se conectó a Redux se llamó Presentational , y esto no fue arbitrario. Este término generalmente se refiere a los componentes React que no están directamente conectados a Redux. Simplemente son responsables de la presentación de la interfaz de usuario y hacen esto en función de los accesorios que reciben. Por el contrario, los componentes del contenedor están conectados a Redux. Estos son generalmente responsables de enviar acciones a la tienda y, a menudo, pasan el estado de la tienda a componentes secundarios como accesorios. +
    + +## Instructions +
    +El editor de código tiene todo el código que has escrito en esta sección hasta ahora. El único cambio es que el componente React se renombra a Presentational . Cree un nuevo componente que se mantenga en una constante llamada Container que use connect para conectar el componente Presentational a Redux. Luego, en AppWrapper , renderice el componente React Redux Provider . Pase a Provider la store Redux como utilería y renderice Container como un niño. Una vez que todo esté configurado, verás nuevamente la aplicación de mensajes renderizada en la página. +
    + +## Tests +
    + +```yml +tests: + - text: El AppWrapper debe renderizar a la página. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("AppWrapper").length === 1; })(), "The AppWrapper should render to the page.");' + - text: 'El componente de Presentational debe representar un h2 , input , button y ul elementos.' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("Presentational").length === 1; })(), "The Presentational component should render an h2, input, button, and ul elements.");' + - text: 'El componente de Presentational debe representar un h2 , input , button y ul elementos.' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); return ( PresentationalComponent.find("div").length === 1 && PresentationalComponent.find("h2").length === 1 && PresentationalComponent.find("button").length === 1 && PresentationalComponent.find("ul").length === 1 ); })(), "The Presentational component should render an h2, input, button, and ul elements.");' + - text: El componente de Presentational debe recibir messages de la tienda de Redux como prop. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), "The Presentational component should receive messages from the Redux store as a prop.");' + - text: El componente de Presentational debe recibir el creador de la acción submitMessage como prop. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === "function"; })(), "The Presentational component should receive the submitMessage action creator as a prop.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// Redux: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message: message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); + +// React: +class Presentational extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + const currentMessage = this.state.input; + this.setState({ + input: ", + messages: this.state.messages.concat(currentMessage) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; + +// React-Redux: +const mapStateToProps = (state) => { + return { messages: state } +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (newMessage) => { + dispatch(addMessage(newMessage)) + } + } +}; + +const Provider = ReactRedux.Provider; +const connect = ReactRedux.connect; + +// define the Container component here: + + +class AppWrapper extends React.Component { + constructor(props) { + super(props); + } + render() { + // complete the return statement: + return (null); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +// Redux: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message: message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); + +// React: +class Presentational extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + const currentMessage = this.state.input; + this.setState({ + input: ", + messages: this.state.messages.concat(currentMessage) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; + +// React-Redux: +const mapStateToProps = (state) => { + return { messages: state } +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (newMessage) => { + dispatch(addMessage(newMessage)) + } + } +}; + +const Provider = ReactRedux.Provider; +const connect = ReactRedux.connect; + +// define the Container component here: +const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational); + +class AppWrapper extends React.Component { + constructor(props) { + super(props); + } + render() { + // complete the return statement: + return ( + + + + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-local-state-into-redux.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-local-state-into-redux.spanish.md new file mode 100644 index 0000000000..3cabe87650 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-local-state-into-redux.spanish.md @@ -0,0 +1,266 @@ +--- +id: 5a24c314108439a4d4036149 +title: Extract Local State into Redux +localeTitle: Extraer el estado local en Redux +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ya casi terminas! Recuerde que escribió todo el código de Redux para que Redux pudiera controlar la administración del estado de su aplicación de mensajes React. Ahora que Redux está conectado, debe extraer la administración del estado del componente de Presentational y en Redux. Actualmente, tiene Redux conectado, pero está manejando el estado localmente dentro del componente de Presentational . +
    + +## Instructions +
    +En el componente Presentational , primero, elimine la propiedad de messages en el state local. Estos mensajes serán gestionados por Redux. A continuación, modifique el método submitMessage() para que submitNewMessage() desde this.props , y pase la entrada del mensaje actual del state local como un argumento. Como también eliminó los messages del estado local, elimine la propiedad de messages de la llamada a this.setState() aquí. Finalmente, modifique el método render() para que se asigne sobre los mensajes recibidos de los props lugar del state . +Una vez que se realicen estos cambios, la aplicación continuará funcionando de la misma manera, excepto que Redux administra el estado. Este ejemplo también ilustra cómo un componente puede tener un state local: su componente aún realiza un seguimiento local de las entradas del usuario en su propio state . Puede ver cómo Redux proporciona un marco de administración de estado útil sobre React. Obtuvo el mismo resultado utilizando solo el estado local de React al principio, y esto generalmente es posible con aplicaciones simples. Sin embargo, a medida que sus aplicaciones se vuelven más grandes y complejas, también lo hace la administración de su estado, y este es el problema que Redux resuelve. +
    + +## Tests +
    + +```yml +tests: + - text: El AppWrapper debe renderizar a la página. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("AppWrapper").length === 1; })(), "The AppWrapper should render to the page.");' + - text: 'El componente de Presentational debe representar un h2 , input , button y ul elementos.' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("Presentational").length === 1; })(), "The Presentational component should render an h2, input, button, and ul elements.");' + - text: 'El componente de Presentational debe representar un h2 , input , button y ul elementos.' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); return ( PresentationalComponent.find("div").length === 1 && PresentationalComponent.find("h2").length === 1 && PresentationalComponent.find("button").length === 1 && PresentationalComponent.find("ul").length === 1 ); })(), "The Presentational component should render an h2, input, button, and ul elements.");' + - text: El componente de Presentational debe recibir messages de la tienda de Redux como prop. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); const props = PresentationalComponent.props(); return Array.isArray(props.messages); })(), "The Presentational component should receive messages from the Redux store as a prop.");' + - text: El componente de Presentational debe recibir el creador de la acción submitMessage como prop. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalComponent = mockedComponent.find("Presentational"); const props = PresentationalComponent.props(); return typeof props.submitNewMessage === "function"; })(), "The Presentational component should receive the submitMessage action creator as a prop.");' + - text: 'El estado del componente Presentational debe contener una propiedad, input , que se inicializa en una cadena vacía.' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const PresentationalState = mockedComponent.find("Presentational").instance().state; return typeof PresentationalState.input === "string" && Object.keys(PresentationalState).length === 1; })(), "The state of the Presentational component should contain one property, input, which is initialized to an empty string.");' + - text: Escribir en el elemento de input debe actualizar el estado del componente de Presentational . + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const testValue = "__MOCK__INPUT__"; const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); let initialInput = mockedComponent.find("Presentational").find("input"); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); const updatedInput = updated.find("Presentational").find("input"); assert(initialInput.props().value === "" && updatedInput.props().value === "__MOCK__INPUT__", "Typing in the input element should update the state of the Presentational component."); }; ' + - text: El envío del submitMessage en el componente de Presentational debe actualizar el almacén de Redux y borrar la entrada en el estado local. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find("Presentational").props(); const testValue = "__TEST__EVENT__INPUT__"; const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find("input").props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find("Presentational").props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find("input").props().value === "", "Dispatching the submitMessage on the Presentational component should update Redux store and clear the input in local state."); }; ' + - text: El componente de Presentational debe representar los messages del almacén de Redux. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); let beforeProps = mockedComponent.find("Presentational").props(); const testValue = "__TEST__EVENT__INPUT__"; const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const clickButton = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterChange = await changed(); const afterChangeInput = afterChange.find("input").props().value; const afterClick = await clickButton(); const afterProps = mockedComponent.find("Presentational").props(); assert(beforeProps.messages.length === 0 && afterChangeInput === testValue && afterProps.messages.pop() === testValue && afterClick.find("input").props().value === "" && afterClick.find("ul").childAt(0).text() === testValue, "The Presentational component should render the messages from the Redux store."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// Redux: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message: message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); + +// React: +const Provider = ReactRedux.Provider; +const connect = ReactRedux.connect; + +// Change code below this line +class Presentational extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + this.setState({ + input: ", + messages: this.state.messages.concat(this.state.input) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; +// Change code above this line + +const mapStateToProps = (state) => { + return {messages: state} +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (message) => { + dispatch(addMessage(message)) + } + } +}; + +const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational); + +class AppWrapper extends React.Component { + render() { + return ( + + + + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +// Redux: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message: message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); + +// React: +const Provider = ReactRedux.Provider; +const connect = ReactRedux.connect; + +// Change code below this line +class Presentational extends React.Component { + constructor(props) { + super(props); + this.state = { + input: " + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + this.props.submitNewMessage(this.state.input); + this.setState({ + input: " + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.props.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; +// Change code above this line + +const mapStateToProps = (state) => { + return {messages: state} +}; + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: (message) => { + dispatch(addMessage(message)) + } + } +}; + +const Container = connect(mapStateToProps, mapDispatchToProps)(Presentational); + +class AppWrapper extends React.Component { + render() { + return ( + + + + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-state-logic-to-redux.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-state-logic-to-redux.spanish.md new file mode 100644 index 0000000000..3ad88a7957 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/extract-state-logic-to-redux.spanish.md @@ -0,0 +1,87 @@ +--- +id: 5a24c314108439a4d4036143 +title: Extract State Logic to Redux +localeTitle: Extraer la lógica de estado para redux +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ahora que terminó el componente React, necesita mover la lógica que está ejecutando localmente en su state a Redux. Este es el primer paso para conectar la aplicación React simple a Redux. La única funcionalidad que tiene su aplicación es agregar nuevos mensajes del usuario a una lista desordenada. El ejemplo es simple para demostrar cómo React y Redux trabajan juntos. +
    + +## Instructions +
    +Primero, defina un tipo de acción 'AGREGAR' y ajústelo a una constante ADD . A continuación, defina un creador de acción addMessage() que crea la acción para agregar un mensaje. Deberá pasar un message a este creador de acción e incluir el mensaje en la action devuelta. +Luego cree un reductor llamado messageReducer() que maneje el estado de los mensajes. El estado inicial debe ser igual a una matriz vacía. Este reductor debe agregar un mensaje a la matriz de mensajes retenidos o devolver el estado actual. Finalmente, crea tu tienda Redux y pásale el reductor. +
    + +## Tests +
    + +```yml +tests: + - text: La constante ADD debe existir y mantener un valor igual a la cadena ADD + testString: 'assert(ADD === "ADD", "The const ADD should exist and hold a value equal to the string ADD");' + - text: El creador de la acción addMessage debería devolver un objeto con un type igual a ADD y un mensaje igual al mensaje que se pasa. + testString: 'assert((function() { const addAction = addMessage("__TEST__MESSAGE__"); return addAction.type === ADD && addAction.message === "__TEST__MESSAGE__"; })(), "The action creator addMessage should return an object with type equal to ADD and message equal to the message that is passed in.");' + - text: messageReducer debería ser una función. + testString: 'assert(typeof messageReducer === "function", "messageReducer should be a function.");' + - text: El almacén debe existir y tener un estado inicial establecido en una matriz vacía. + testString: 'assert((function() { const initialState = store.getState(); return typeof store === "object" && initialState.length === 0; })(), "The store should exist and have an initial state set to an empty array.");' + - text: El envío de addMessage contra la tienda debe agregar de manera inmutable un nuevo mensaje a la matriz de mensajes mantenidos en estado. + testString: 'assert((function() { const initialState = store.getState(); const isFrozen = DeepFreeze(initialState); store.dispatch(addMessage("__A__TEST__MESSAGE")); const addState = store.getState(); return (isFrozen && addState[0] === "__A__TEST__MESSAGE"); })(), "Dispatching addMessage against the store should immutably add a new message to the array of messages held in state.");' + - text: El messageReducer debería devolver el estado actual si se llama con cualquier otra acción. + testString: 'assert((function() { const addState = store.getState(); store.dispatch({type: "FAKE_ACTION"}); const testState = store.getState(); return (addState === testState); })(), "The messageReducer should return the current state if called with any other actions.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// define ADD, addMessage(), messageReducer(), and store here: + +``` + +
    + + + +
    + +## Solution +
    + + +```js +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/getting-started-with-react-redux.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/getting-started-with-react-redux.spanish.md new file mode 100644 index 0000000000..d59b0fc192 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/getting-started-with-react-redux.spanish.md @@ -0,0 +1,86 @@ +--- +id: 5a24c314108439a4d4036141 +title: Getting Started with React Redux +localeTitle: Empezando con React Redux +challengeType: 6 +isRequired: false +--- + +## Description +
    +Esta serie de desafíos presenta cómo utilizar Redux con React. Primero, aquí hay una revisión de algunos de los principios clave de cada tecnología. React es una biblioteca de vistas que proporciona datos, luego la convierte de forma eficiente y predecible. Redux es un marco de administración de estado que puede utilizar para simplificar la administración del estado de su aplicación. Normalmente, en una aplicación React Redux, creas una sola tienda Redux que administra el estado de toda tu aplicación. Sus componentes de React se suscriben solo a los datos en la tienda que son relevantes para su función. Luego, envía acciones directamente desde los componentes de React, que luego activan las actualizaciones del almacén. +Aunque los componentes de React pueden administrar su propio estado localmente, cuando tiene una aplicación compleja, generalmente es mejor mantener el estado de la aplicación en una sola ubicación con Redux. Hay excepciones cuando los componentes individuales pueden tener un estado local específico solo para ellos. Finalmente, debido a que Redux no está diseñado para funcionar con React out of the box, debe usar el paquete react-redux . Le proporciona una forma de pasar el state Redux y dispatch a sus componentes React como props . +En los próximos desafíos, primero, creará un componente React simple que le permite ingresar nuevos mensajes de texto. Estos se agregan a una matriz que se muestra en la vista. Esto debería ser una buena revisión de lo que aprendiste en las lecciones de React. A continuación, creará un almacén de Redux y acciones que administran el estado de la matriz de mensajes. Finalmente, utilizará react-redux para conectar la tienda Redux con su componente, extrayendo así el estado local a la tienda Redux. +
    + +## Instructions +
    +Comience con un componente DisplayMessages . Agregue un constructor a este componente e inicialícelo con un estado que tenga dos propiedades: input , que se establece en una cadena vacía, y messages , que se establece en una matriz vacía. +
    + +## Tests +
    + +```yml +tests: + - text: El componente DisplayMessages debe representar un elemento div vacío. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); return mockedComponent.find("div").text() === "" })(), "The DisplayMessages component should render an empty div element.");' + - text: 'El constructor de DisplayMessages debe llamarse correctamente con super , pasando en props '. + testString: 'getUserInput => assert((function() { const noWhiteSpace = getUserInput("index").replace(/\s/g,""); return noWhiteSpace.includes("constructor(props)") && noWhiteSpace.includes("super(props"); })(), "The DisplayMessages constructor should be called properly with super, passing in props.");' + - text: 'El componente DisplayMessages debe tener un estado inicial igual a {input: "", messages: []} .' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return typeof initialState === "object" && initialState.input === "" && Array.isArray(initialState.messages) && initialState.messages.length === 0; })(), "The DisplayMessages component should have an initial state equal to {input: "", messages: []}.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class DisplayMessages extends React.Component { + // change code below this line + + // change code above this line + render() { + return
    + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class DisplayMessages extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + } + render() { + return
    + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/manage-state-locally-first.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/manage-state-locally-first.spanish.md new file mode 100644 index 0000000000..a2d424f4f0 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/manage-state-locally-first.spanish.md @@ -0,0 +1,135 @@ +--- +id: 5a24c314108439a4d4036142 +title: Manage State Locally First +localeTitle: Administrar el estado localmente primero +challengeType: 6 +isRequired: false +--- + +## Description +
    +Aquí terminarás de crear el componente DisplayMessages . +
    + +## Instructions +
    +Primero, en el método render() , haga que el componente procese un elemento de input , un elemento de button y un elemento ul . Cuando el elemento de input cambia, debe activar un método handleChange() . Además, el elemento de input debe representar el valor de la input que se encuentra en el estado del componente. El elemento de button debe activar un método submitMessage() cuando se hace clic. +Segundo, escribe estos dos métodos. El método handleChange() debe actualizar la input con lo que el usuario está escribiendo. El método submitMessage() debe concatenar el mensaje actual (almacenado en la input ) a la matriz de messages en el estado local, y borrar el valor de la input . +Finalmente, use la ul para mapear sobre el conjunto de messages y procesarlos en la pantalla como una lista de elementos li . +
    + +## Tests +
    + +```yml +tests: + - text: 'El componente DisplayMessages debería inicializarse con un estado igual a { input: "", messages: [] } .' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const initialState = mockedComponent.state(); return ( typeof initialState === "object" && initialState.input === "" && initialState.messages.length === 0); })(), "The DisplayMessages component should initialize with a state equal to { input: "", messages: [] }.");' + - text: "El componente DisplayMessages debería generar un div contenga un elemento h2 , un elemento de button , un elemento ul y elementos li como elementos li ". + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const state = () => { mockedComponent.setState({messages: ["__TEST__MESSAGE"]}); return waitForIt(() => mockedComponent )}; const updated = await state(); assert(updated.find("div").length === 1 && updated.find("h2").length === 1 && updated.find("button").length === 1 && updated.find("ul").length === 1, "The DisplayMessages component should render a div containing an h2 element, a button element, a ul element, and li elements as children."); }; ' + - text: El elemento de input debe representar el valor de input en estado local. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const testValue = "__TEST__EVENT__INPUT"; const changed = () => { causeChange(mockedComponent, testValue); return waitForIt(() => mockedComponent )}; const updated = await changed(); assert(updated.find("input").props().value === testValue, "The input element should render the value of input in local state."); }; ' + - text: Al llamar al método handleChange debe actualizar el valor de input en estado a la entrada actual. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = "__TEST__EVENT__MESSAGE__"; const changed = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const afterInput = await changed(); assert(initialState.input === "" && afterInput.state().input === "__TEST__EVENT__MESSAGE__", "Calling the method handleChange should update the input value in state to the current input."); }; ' + - text: Al hacer clic en el botón Add message se debe llamar al método submitMessage que debe agregar la input actual a la matriz de messages en el estado. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage_1 = "__FIRST__MESSAGE__"; const firstChange = () => { causeChange(mockedComponent, testMessage_1); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit_1 = await firstSubmit(); const submitState_1 = afterSubmit_1.state(); const testMessage_2 = "__SECOND__MESSAGE__"; const secondChange = () => { causeChange(mockedComponent, testMessage_2); return waitForIt(() => mockedComponent )}; const secondResult = await secondChange(); const secondSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit_2 = await secondSubmit(); const submitState_2 = afterSubmit_2.state(); assert(initialState.messages.length === 0 && submitState_1.messages.length === 1 && submitState_2.messages.length === 2 && submitState_2.messages[1] === testMessage_2, "Clicking the Add message button should call the method submitMessage which should add the current input to the messages array in state."); }; ' + - text: El método submitMessage debería borrar la entrada actual. + testString: 'async () => { const mockedComponent = Enzyme.mount(React.createElement(DisplayMessages)); const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const causeChange = (c, v) => c.find("input").simulate("change", { target: { value: v }}); const initialState = mockedComponent.state(); const testMessage = "__FIRST__MESSAGE__"; const firstChange = () => { causeChange(mockedComponent, testMessage); return waitForIt(() => mockedComponent )}; const firstResult = await firstChange(); const firstState = firstResult.state(); const firstSubmit = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent )}; const afterSubmit = await firstSubmit(); const submitState = afterSubmit.state(); assert(firstState.input === testMessage && submitState.input === "", "The submitMessage method should clear the current input."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class DisplayMessages extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + } + // add handleChange() and submitMessage() methods here + + render() { + return ( +
    +

    Type in a new Message:

    + { /* render an input, button, and ul here */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class DisplayMessages extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + const currentMessage = this.state.input; + this.setState({ + input: ", + messages: this.state.messages.concat(currentMessage) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-dispatch-to-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-dispatch-to-props.spanish.md new file mode 100644 index 0000000000..21db2f397f --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-dispatch-to-props.spanish.md @@ -0,0 +1,85 @@ +--- +id: 5a24c314108439a4d4036146 +title: Map Dispatch to Props +localeTitle: Mapa de Despacho a Puntales +challengeType: 6 +isRequired: false +--- + +## Description +
    +La función mapDispatchToProps() se usa para proporcionar creadores de acción específicos a sus componentes React para que puedan enviar acciones contra el almacén de Redux. Es similar en estructura a la función mapStateToProps() que escribió en el último desafío. Devuelve un objeto que asigna acciones de despacho a nombres de propiedades, que se convierten en props componentes. Sin embargo, en lugar de devolver una parte del state , cada propiedad devuelve una función que llama el dispatch con un creador de acción y cualquier información de acción relevante. Tiene acceso a este dispatch porque se pasa a mapDispatchToProps() como un parámetro cuando define la función, al igual que pasó el state a mapStateToProps() . Detrás de escena, React Redux está utilizando store.dispatch() Redux para realizar estos despachos con mapDispatchToProps() . Esto es similar a cómo utiliza store.subscribe() para los componentes que se asignan al state . +Por ejemplo, tiene un creador de acción loginUser() que toma un username como una carga útil de acción. El objeto devuelto desde mapDispatchToProps() para este creador de acción se vería algo así como: +
    {
      submitLoginUser: function(username) {
        dispatch(loginUser(username));
      }
    }
    +
    + +## Instructions +
    +El editor de código proporciona un creador de acción llamado addMessage() . Escriba la función mapDispatchToProps() que toma el dispatch como un argumento, luego devuelve un objeto. El objeto debe tener una propiedad submitNewMessage establecida en la función de envío, que toma un parámetro para que el nuevo mensaje se agregue cuando distribuya addMessage() . +
    + +## Tests +
    + +```yml +tests: + - text: addMessage debe devolver un objeto con claves de type y message . + testString: 'assert((function() { const addMessageTest = addMessage(); return ( addMessageTest.hasOwnProperty("type") && addMessageTest.hasOwnProperty("message")); })(), "addMessage should return an object with keys type and message.");' + - text: mapDispatchToProps debería ser una función. + testString: 'assert(typeof mapDispatchToProps === "function", "mapDispatchToProps should be a function.");' + - text: mapDispatchToProps debe devolver un objeto. + testString: 'assert(typeof mapDispatchToProps() === "object", "mapDispatchToProps should return an object.");' + - text: El envío de addMessage con submitNewMessage desde mapDispatchToProps debe devolver un mensaje a la función de envío. + testString: 'assert((function() { let testAction; const dispatch = (fn) => { testAction = fn; }; let dispatchFn = mapDispatchToProps(dispatch); dispatchFn.submitNewMessage("__TEST__MESSAGE__"); return (testAction.type === "ADD" && testAction.message === "__TEST__MESSAGE__"); })(), "Dispatching addMessage with submitNewMessage from mapDispatchToProps should return a message to the dispatch function.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const addMessage = (message) => { + return { + type: 'ADD', + message: message + } +}; + +// change code below this line + +``` + +
    + + + +
    + +## Solution +
    + + +```js +const addMessage = (message) => { + return { + type: 'ADD', + message: message + } +}; + +// change code below this line + +const mapDispatchToProps = (dispatch) => { + return { + submitNewMessage: function(message) { + dispatch(addMessage(message)); + } + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-state-to-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-state-to-props.spanish.md new file mode 100644 index 0000000000..7a50974272 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/map-state-to-props.spanish.md @@ -0,0 +1,73 @@ +--- +id: 5a24c314108439a4d4036145 +title: Map State to Props +localeTitle: Mapa del estado a los apoyos +challengeType: 6 +isRequired: false +--- + +## Description +
    +El componente Provider permite proporcionar state y dispatch a sus componentes React, pero debe especificar exactamente qué estado y acciones desea. De esta manera, se asegura de que cada componente solo tenga acceso al estado que necesita. Esto se logra creando dos funciones: mapStateToProps() y mapDispatchToProps() . +En estas funciones, declara a qué estados de estado desea acceder y a qué creadores de acción necesita poder enviar. Una vez que estas funciones estén en su lugar, verá cómo utilizar el método React Redux connect para conectarlos a sus componentes en otro desafío. +Nota: Detrás de escena, React Redux usa el método store.subscribe() para implementar mapStateToProps() . +
    + +## Instructions +
    +Crear una función mapStateToProps() . Esta función debe tomar el state como un argumento, luego devolver un objeto que mapea ese estado a nombres de propiedad específicos. Estas propiedades serán accesibles a su componente a través de props . Como este ejemplo mantiene todo el estado de la aplicación en una sola matriz, puede pasar ese estado completo a su componente. Cree un messages propiedad en el objeto que se está devolviendo y configúrelo en state . +
    + +## Tests +
    + +```yml +tests: + - text: El state constante debe ser una matriz vacía. + testString: 'assert(Array.isArray(state) && state.length === 0, "The const state should be an empty array.");' + - text: mapStateToProps debería ser una función. + testString: 'assert(typeof mapStateToProps === "function", "mapStateToProps should be a function.");' + - text: mapStateToProps debe devolver un objeto. + testString: 'assert(typeof mapStateToProps() === "object", "mapStateToProps should return an object.");' + - text: Pasar una matriz como estado a mapStateToProps debería devolver esta matriz asignada a una clave de messages . + testString: 'assert(mapStateToProps(["messages"]).messages.pop() === "messages", "Passing an array as state to mapStateToProps should return this array assigned to a key of messages.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const state = []; + +// change code below this line + +``` + +
    + + + +
    + +## Solution +
    + + +```js +const state = []; + +// change code below this line + +const mapStateToProps = (state) => { + return { + messages: state + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/moving-forward-from-here.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/moving-forward-from-here.spanish.md new file mode 100644 index 0000000000..964a02d4a8 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/moving-forward-from-here.spanish.md @@ -0,0 +1,79 @@ +--- +id: 5a24c314108439a4d403614a +title: Moving Forward From Here +localeTitle: Avanzando desde aquí +challengeType: 6 +isRequired: false +--- + +## Description +
    +Felicitaciones! Terminaste las lecciones sobre React y Redux. Hay un último elemento que vale la pena señalar antes de continuar. Normalmente, no escribirás aplicaciones React en un editor de código como este. Este desafío le da una idea de cómo se ve la sintaxis si está trabajando con npm y un sistema de archivos en su propia máquina. El código debe tener un aspecto similar, excepto por el uso de instrucciones de import (estos detienen todas las dependencias que se le proporcionaron en los desafíos). La sección "Administración de paquetes con npm" cubre npm con más detalle. +Finalmente, escribir el código React y Redux generalmente requiere alguna configuración. Esto puede complicarse rápidamente. Si está interesado en experimentar en su propia máquina, la aplicación +Create React App viene configurada y lista para funcionar. +Alternativamente, puede habilitar Babel como un preprocesador de JavaScript en CodePen, agregar React y ReactDOM como recursos externos de JavaScript, y trabajar allí también. +
    + +## Instructions +
    +Registre el mensaje 'Now I know React and Redux!' a la consola. +
    + +## Tests +
    + +```yml +tests: + - text: El mensaje ¡ Now I know React and Redux! debe estar registrado en la consola. + testString: 'assert(editor.getValue().includes("console.log("Now I know React and Redux!")") || editor.getValue().includes("console.log(\"Now I know React and Redux!\")"), "The message Now I know React and Redux! should be logged to the console.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// import React from 'react' +// import ReactDOM from 'react-dom' +// import { Provider, connect } from 'react-redux' +// import { createStore, combineReducers, applyMiddleware } from 'redux' +// import thunk from 'redux-thunk' + +// import rootReducer from './redux/reducers' +// import App from './components/App' + +// const store = createStore( +// rootReducer, +// applyMiddleware(thunk) +// ); + +// ReactDOM.render( +// +// +// , +// document.getElementById('root') +// ); + +// change code below this line + +``` + +
    + + + +
    + +## Solution +
    + + +```js +console.log('Now I know React and Redux!'); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react.spanish.md new file mode 100644 index 0000000000..4dda16b358 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react-and-redux/use-provider-to-connect-redux-to-react.spanish.md @@ -0,0 +1,229 @@ +--- +id: 5a24c314108439a4d4036144 +title: Use Provider to Connect Redux to React +localeTitle: Usar el Proveedor para Conectar Redux para Reaccionar +challengeType: 6 +isRequired: false +--- + +## Description +
    +En el último desafío, creó un almacén Redux para manejar la matriz de mensajes y creó una acción para agregar nuevos mensajes. El siguiente paso es proporcionar acceso React a la tienda Redux y las acciones que necesita para enviar actualizaciones. React Redux proporciona su paquete react-redux para ayudar a realizar estas tareas. +React Redux proporciona una pequeña API con dos características clave: Provider y connect . Otro reto cubre connect . El Provider es un componente envolvente de React Redux que envuelve su aplicación React. Este contenedor le permite acceder a las funciones de store y dispatch Redux a través de su árbol de componentes. Provider toma dos accesorios, la tienda Redux y los componentes secundarios de su aplicación. La definición del Provider para un componente de la aplicación podría tener este aspecto: +
    <Provider store={store}>
      <App/>
    </Provider>
    +
    + +## Instructions +
    +El editor de código ahora muestra todos sus códigos Redux y React de los últimos desafíos. Incluye la tienda Redux, las acciones y el componente DisplayMessages . La única pieza nueva es el componente AppWrapper en la parte inferior. Utilice este componente de nivel superior para representar al Provider desde ReactRedux , y pase la tienda Redux como prop. Luego renderice el componente DisplayMessages como un elemento secundario. Una vez que hayas terminado, deberías ver tu componente React renderizado en la página. +Nota: React Redux está disponible aquí como una variable global, por lo que puede acceder al Proveedor con notación de puntos. El código en el editor se aprovecha de esto y lo establece en un Provider constante para que lo use en el método de renderizado de AppWrapper . +
    + +## Tests +
    + +```yml +tests: + - text: El AppWrapper debe hacer. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("AppWrapper").length === 1; })(), "The AppWrapper should render.");' + - text: 'El componente contenedor del Provider debe tener una propiedad de la store pasado, igual a la tienda Redux'. + testString: 'getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return getUserInput("index").replace(/\s/g,"").includes(""); })(), "The Provider wrapper component should have a prop of store passed to it, equal to the Redux store.");' + - text: DisplayMessages debería renderizarse como un elemento secundario de AppWrapper . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("AppWrapper").find("DisplayMessages").length === 1; })(), "DisplayMessages should render as a child of AppWrapper.");' + - text: 'El componente DisplayMessages debe representar un elemento h2, input, button y ul .' + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find("div").length === 1 && mockedComponent.find("h2").length === 1 && mockedComponent.find("button").length === 1 && mockedComponent.find("ul").length === 1; })(), "The DisplayMessages component should render an h2, input, button, and ul element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// Redux Code: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + + + +const store = Redux.createStore(messageReducer); + +// React Code: + +class DisplayMessages extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + const currentMessage = this.state.input; + this.setState({ + input: ", + messages: this.state.messages.concat(currentMessage) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; + +const Provider = ReactRedux.Provider; + +class AppWrapper extends React.Component { + // render the Provider here + + // change code above this line +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +// Redux Code: +const ADD = 'ADD'; + +const addMessage = (message) => { + return { + type: ADD, + message + } +}; + +const messageReducer = (state = [], action) => { + switch (action.type) { + case ADD: + return [ + ...state, + action.message + ]; + default: + return state; + } +}; + +const store = Redux.createStore(messageReducer); + +// React Code: + +class DisplayMessages extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + messages: [] + } + this.handleChange = this.handleChange.bind(this); + this.submitMessage = this.submitMessage.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + submitMessage() { + const currentMessage = this.state.input; + this.setState({ + input: ", + messages: this.state.messages.concat(currentMessage) + }); + } + render() { + return ( +
    +

    Type in a new Message:

    +
    + +
      + {this.state.messages.map( (message, idx) => { + return ( +
    • {message}
    • + ) + }) + } +
    +
    + ); + } +}; + +const Provider = ReactRedux.Provider; + +class AppWrapper extends React.Component { + // change code below this line + render() { + return ( + + + + ); + } + // change code above this line +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/access-props-using-this.props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/access-props-using-this.props.spanish.md new file mode 100644 index 0000000000..4caf2d5c54 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/access-props-using-this.props.spanish.md @@ -0,0 +1,135 @@ +--- +id: 5a24c314108439a4d403616e +title: Access Props Using this.props +localeTitle: Acceder a los apoyos usando this.props +challengeType: 6 +isRequired: false +--- + +## Description +
    +Los últimos varios desafíos cubrieron las formas básicas de pasar apoyos a componentes secundarios. Pero, ¿qué sucede si el componente secundario al que le está pasando una propuesta es un componente de clase ES6, en lugar de un componente funcional sin estado? El componente de clase ES6 utiliza una convención ligeramente diferente para acceder a accesorios. +Cada vez que refiera a un componente de clase dentro de sí mismo, use this palabra clave. Para acceder a los apoyos dentro de un componente de clase, que Prefacio el código que se utiliza para acceder a ella con this . Por ejemplo, si un componente de clase ES6 tiene una propiedad llamada data , escribe {this.props.data} en JSX. +
    + +## Instructions +
    +Renderice una instancia del componente ReturnTempPassword en el componente principal ResetPassword . Aquí, ReturnTempPassword a ReturnTempPassword un prop de tempPassword y asígnele un valor de una cadena que tenga al menos 8 caracteres de longitud. Dentro del hijo, ReturnTempPassword , acceda a la propiedad tempPassword dentro de las etiquetas strong para asegurarse de que el usuario vea la contraseña temporal. +
    + +## Tests +
    + +```yml +tests: + - text: El componente ResetPassword debe devolver un único elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().type() === "div"; })(), "The ResetPassword component should return a single div element.");' + - text: El cuarto hijo de ResetPassword debe ser el componente ReturnTempPassword . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.children().childAt(3).name() === "ReturnTempPassword"; })(), "The fourth child of ResetPassword should be the ReturnTempPassword component.");' + - text: El componente ReturnTempPassword debe tener un prop llamado tempPassword . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find("ReturnTempPassword").props().tempPassword; })(), "The ReturnTempPassword component should have a prop called tempPassword.");' + - text: El prop tempPassword de ReturnTempPassword debe ser igual a una cadena de al menos 8 caracteres. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); const temp = mockedComponent.find("ReturnTempPassword").props().tempPassword; return typeof temp === "string" && temp.length >= 8; })(), "The tempPassword prop of ReturnTempPassword should be equal to a string of at least 8 characters.");' + - text: El componente ReturnTempPassword debe mostrar la contraseña que crea como el prop tempPassword dentro de strong etiquetas strong . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); return mockedComponent.find("strong").text() === mockedComponent.find("ReturnTempPassword").props().tempPassword; })(), "The ReturnTempPassword component should display the password you create as the tempPassword prop within strong tags.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class ReturnTempPassword extends React.Component { + constructor(props) { + super(props); + + } + render() { + return ( +
    + { /* change code below this line */ } +

    Your temporary password is:

    + { /* change code above this line */ } +
    + ); + } +}; + +class ResetPassword extends React.Component { + constructor(props) { + super(props); + + } + render() { + return ( +
    +

    Reset Password

    +

    We've generated a new temporary password for you.

    +

    Please reset this password from your account settings ASAP.

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class ReturnTempPassword extends React.Component { + constructor(props) { + super(props); + + } + render() { + return ( +
    +

    Your temporary password is: {this.props.tempPassword}

    +
    + ); + } +}; + +class ResetPassword extends React.Component { + constructor(props) { + super(props); + + } + render() { + return ( +
    +

    Reset Password

    +

    We've generated a new temporary password for you.

    +

    Please reset this password from your account settings ASAP.

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/add-comments-in-jsx.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/add-comments-in-jsx.spanish.md new file mode 100644 index 0000000000..ff11f748c1 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/add-comments-in-jsx.spanish.md @@ -0,0 +1,79 @@ +--- +id: 5a24bbe0dba28a8d3cbd4c5e +title: Add Comments in JSX +localeTitle: Añadir comentarios en JSX +challengeType: 6 +isRequired: false +--- + +## Description +
    +JSX es una sintaxis que se compila en JavaScript válido. A veces, para facilitar la lectura, es posible que necesite agregar comentarios a su código. Como la mayoría de los lenguajes de programación, JSX tiene su propia manera de hacer esto. +Para colocar comentarios dentro de JSX, usa la sintaxis {/* */} para envolver el texto del comentario. +
    + +## Instructions +
    +El editor de código tiene un elemento JSX similar al que creaste en el último desafío. Agregue un comentario en algún lugar dentro del elemento div proporcionado, sin modificar los elementos h1 o p existentes. +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debe devolver un elemento div . + testString: 'assert(JSX.type === "div", "The constant JSX should return a div element.");' + - text: El div debe contener una etiqueta h1 como el primer elemento. + testString: 'assert(JSX.props.children[0].type === "h1", "The div should contain an h1 tag as the first element.");' + - text: El div debe contener una etiqueta p como el segundo elemento. + testString: 'assert(JSX.props.children[1].type === "p", "The div should contain a p tag as the second element.");' + - text: El JSX debe incluir un comentario. + testString: 'getUserInput => assert(getUserInput("index").includes("/*") && getUserInput("index").includes("*/"), "The JSX should include a comment.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const JSX = ( +
    +

    This is a block of JSX

    +

    Here's a subtitle

    +
    +); +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const JSX = ( +
    +

    This is a block of JSX

    + { /* this is a JSX comment */ } +

    Here's a subtitle

    +
    ); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/add-event-listeners.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/add-event-listeners.spanish.md new file mode 100644 index 0000000000..0fae059bb0 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/add-event-listeners.spanish.md @@ -0,0 +1,139 @@ +--- +id: 5a24c314108439a4d403617e +title: Add Event Listeners +localeTitle: Añadir escuchas de eventos +challengeType: 6 +isRequired: false +--- + +## Description +
    +El método componentDidMount() también es el mejor lugar para adjuntar cualquier escucha de eventos que necesite agregar para una funcionalidad específica. React proporciona un sistema de eventos sintéticos que envuelve el sistema de eventos nativo presente en los navegadores. Esto significa que el sistema de eventos sintéticos se comporta exactamente igual sin importar el navegador del usuario, incluso si los eventos nativos pueden comportarse de manera diferente entre diferentes navegadores. +Ya ha estado utilizando algunos de estos controladores de eventos sintéticos como onClick() . El sistema de eventos sintéticos de React es excelente para la mayoría de las interacciones que administrará en los elementos DOM. Sin embargo, si desea adjuntar un controlador de eventos al documento o los objetos de la ventana, debe hacerlo directamente. +
    + +## Instructions +
    +Adjunte un detector de eventos en el método componentDidMount() para eventos keydown y keydown que estos eventos activen la devolución de llamada handleKeyPress() . Puede usar document.addEventListener() que toma el evento (entre comillas) como primer argumento y la devolución de llamada como segundo argumento. +Luego, en componentWillUnmount() , elimine este mismo detector de eventos. Puede pasar los mismos argumentos a document.removeEventListener() . Es una buena práctica usar este método de ciclo de vida para limpiar los componentes de React antes de que se desmonten y destruyan. La eliminación de escuchas de eventos es un ejemplo de una de estas acciones de limpieza. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debe generar un elemento div que envuelva una etiqueta h1 . + testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("div").children().find("h1").length === 1; })(), "MyComponent should render a div element which wraps an h1 tag.");' + - text: Se debe adjuntar un detector de keydown al documento en componentDidMount . + testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const didMountString = mockedComponent.instance().componentDidMount.toString(); return new RegExp("document\.addEventListener(.|\n|\r)+keydown(.|\n|\r)+this\.handleKeyPress").test(didMountString); })(), "A keydown listener should be attached to the document in componentDidMount.");' + - text: El oyente keydown debe eliminarse del documento en componentWillUnmount . + testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const willUnmountString = mockedComponent.instance().componentWillUnmount.toString(); return new RegExp("document\.removeEventListener(.|\n|\r)+keydown(.|\n|\r)+this\.handleKeyPress").test(willUnmountString); })(), "The keydown listener should be removed from the document in componentWillUnmount.");' + - text: "Una vez que el componente se haya montado, al presionar enter se actualizará su estado y la etiqueta h1 representada". + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const beforeState = mockedComponent.state("message"); const beforeText = mockedComponent.find("h1").text(); const pressEnterKey = () => { mockedComponent.instance().handleKeyPress({ keyCode: 13 }); return waitForIt(() => { mockedComponent.update(); return { state: mockedComponent.state("message"), text: mockedComponent.find("h1").text()}; });}; const afterKeyPress = await pressEnterKey(); assert(beforeState !== afterKeyPress.state && beforeText !== afterKeyPress.text, "Once the component has mounted, pressing enter should update its state and the rendered h1 tag."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + message: " + }; + this.handleEnter = this.handleEnter.bind(this); + this.handleKeyPress = this.handleKeyPress.bind(this); + } + // change code below this line + componentDidMount() { + + } + componentWillUnmount() { + + } + // change code above this line + handleEnter() { + this.setState({ + message: this.state.message + 'You pressed the enter key! ' + }); + } + handleKeyPress(event) { + if (event.keyCode === 13) { + this.handleEnter(); + } + } + render() { + return ( +
    +

    {this.state.message}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + message: " + }; + this.handleKeyPress = this.handleKeyPress.bind(this); + this.handleEnter = this.handleEnter.bind(this); } + componentDidMount() { + // change code below this line + document.addEventListener('keydown', this.handleKeyPress); + // change code above this line + } + componentWillUnmount() { + // change code below this line + document.removeEventListener('keydown', this.handleKeyPress); + // change code above this line + } + handleEnter() { + this.setState({ + message: this.state.message + 'You pressed the enter key! ' + }); + } + handleKeyPress(event) { + if (event.keyCode === 13) { + this.handleEnter(); + } + } + render() { + return ( +
    +

    {this.state.message}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/add-inline-styles-in-react.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/add-inline-styles-in-react.spanish.md new file mode 100644 index 0000000000..ecd43810d3 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/add-inline-styles-in-react.spanish.md @@ -0,0 +1,100 @@ +--- +id: 5a24c314108439a4d4036182 +title: Add Inline Styles in React +localeTitle: Añadir estilos en línea en reaccionar +challengeType: 6 +isRequired: false +--- + +## Description +
    +Es posible que haya notado en el último desafío que existían otras diferencias de sintaxis con respecto a los estilos HTML en línea además del atributo de style establecido en un objeto de JavaScript. Primero, los nombres de ciertas propiedades de estilo CSS usan camel case. Por ejemplo, el último desafío establecer el tamaño de la fuente con fontSize en lugar de font-size . Las palabras con guión, como font-size son sintaxis no válida para las propiedades de los objetos de JavaScript, por lo que React usa un caso de camello Como regla general, todas las propiedades de estilo con guión se escriben utilizando el caso camel en JSX. +Se supone que todas las unidades de longitud de valor de propiedad (como height , width y fontSize ) están en px menos que se especifique lo contrario. Si desea usar em , por ejemplo, envuelva el valor y las unidades entre comillas, como {fontSize: "4em"} . Aparte de los valores de longitud que predeterminan a px , todos los demás valores de propiedad deben incluirse entre comillas. +
    + +## Instructions +
    +Si tiene un gran conjunto de estilos, puede asignar un object estilo a una constante para mantener su código organizado. Descomente la constante de styles y declare un object con tres propiedades de estilo y sus valores. Dale al div un color de "purple" , un tamaño de fuente de 40 , y un borde de "2px solid purple" . A continuación, establezca el atributo de style igual a la constante de styles . +
    + +## Tests +
    + +```yml +tests: + - text: La variable de styles debe ser un object con tres propiedades. + testString: 'assert(Object.keys(styles).length === 3, "The styles variable should be an object with three properties.");' + - text: La variable de styles debe tener una propiedad de color establecida en un valor de purple . + testString: 'assert(styles.color === "purple", "The styles variable should have a color property set to a value of purple.");' + - text: La variable de styles debe tener una propiedad fontSize establecida en un valor de 40 . + testString: 'assert(styles.fontSize === 40, "The styles variable should have a fontSize property set to a value of 40.");' + - text: La variable de styles debe tener una propiedad de border establecida en un valor de 2px solid purple . + testString: 'assert(styles.border === "2px solid purple", "The styles variable should have a border property set to a value of 2px solid purple.");' + - text: El componente debe representar un elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return mockedComponent.type() === "div"; })(), "The component should render a div element.");' + - text: El elemento div debe tener sus estilos definidos por el objeto de styles . + testString: 'assert((function() { const mockedComponent = Enzyme.shallow(React.createElement(Colorful)); return (mockedComponent.props().style.color === "purple" && mockedComponent.props().style.fontSize === 40 && mockedComponent.props().style.border === "2px solid purple"); })(), "The div element should have its styles defined by the styles object.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +// const styles = +// change code above this line +class Colorful extends React.Component { + render() { + // change code below this line + return ( +
    Style Me!
    + ); + // change code above this line + } +}; + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const styles = { + color: "purple", + fontSize: 40, + border: "2px solid purple" +}; +// change code above this line +class Colorful extends React.Component { + render() { + // change code below this line + return ( +
    Style Me!
    + // change code above this line + ); + } +}; + +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/bind-this-to-a-class-method.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/bind-this-to-a-class-method.spanish.md new file mode 100644 index 0000000000..251205f7db --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/bind-this-to-a-class-method.spanish.md @@ -0,0 +1,116 @@ +--- +id: 5a24c314108439a4d4036174 +title: Bind 'this' to a Class Method +localeTitle: Enlazar 'esto' a un método de clase +challengeType: 6 +isRequired: false +--- + +## Description +
    +Además de establecer y actualizar el state , también puede definir métodos para su clase de componente. Un método de clase normalmente necesita usar this palabra clave para poder acceder a las propiedades de la clase (como el state y los props ) dentro del alcance del método. Hay algunas maneras de permitir que sus métodos de clase accedan a this . +Una forma común es vincular de forma explícita this en el constructor por lo que this se une a los métodos de la clase cuando el componente se inicializa. Es posible que haya notado que el último desafío utilizó this.handleClick = this.handleClick.bind(this) para su método handleClick en el constructor. Luego, cuando llama a una función como this.setState() dentro de su método de clase, this refiere a la clase y no quedará undefined . +Nota: this palabra clave es uno de los aspectos más confusos de JavaScript, pero desempeña un papel importante en React. A pesar de que su comportamiento aquí es totalmente normal, estas lecciones no son el lugar para una revisión en profundidad de this así que por favor consulte otras lecciones si lo anterior es confuso. +
    + +## Instructions +
    +El editor de código tiene un componente con un state que realiza un seguimiento de un recuento de elementos. También tiene un método que le permite incrementar este recuento de elementos. Sin embargo, el método no funciona porque está usando this palabra clave que no está definida. Corregir el problema mediante la unión explícitamente this a la addItem() método en el constructor del componente. +A continuación, agregue un controlador de clic al elemento de button en el método de procesamiento. Debería activar el método addItem() cuando el botón recibe un evento de clic. Recuerde que el método que pase al controlador onClick necesita llaves porque debe interpretarse directamente como JavaScript. +Una vez que complete los pasos anteriores, debería poder hacer clic en el botón y ver el incremento en el recuento de elementos en el HTML. +
    + +## Tests +
    + +```yml +tests: + - text: " MyComponent debería devolver un elemento div que envuelva dos elementos, un botón y un elemento h1 , en ese orden". + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).find("div").length === 1 && Enzyme.mount(React.createElement(MyComponent)).find("div").childAt(0).type() === "button" && Enzyme.mount(React.createElement(MyComponent)).find("div").childAt(1).type() === "h1", "MyComponent should return a div element which wraps two elements, a button and an h1 element, in that order.");' + - text: 'El estado de MyComponent debe inicializarse con el par de valores clave { itemCount: 0 } .' + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("itemCount") === 0, "The state of MyComponent should initialize with the key value pair { itemCount: 0 }.");' + - text: Al hacer clic en el elemento del button se debe ejecutar el método addItem e incrementar el estado itemCount en 1 . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ itemCount: 0 }); return waitForIt(() => mockedComponent.state("itemCount")); }; const second = () => { mockedComponent.find("button").simulate("click"); return waitForIt(() => mockedComponent.state("itemCount")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === 0 && secondValue === 1, "Clicking the button element should run the addItem method and increment the state itemCount by 1."); };' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + itemCount: 0 + }; + // change code below this line + + // change code above this line + } + addItem() { + this.setState({ + itemCount: this.state.itemCount + 1 + }); + } + render() { + return ( +
    + { /* change code below this line */ } + + { /* change code above this line */ } +

    Current Item Count: {this.state.itemCount}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + itemCount: 0 + }; + this.addItem = this.addItem.bind(this); + } + addItem() { + this.setState({ + itemCount: this.state.itemCount + 1 + }); + } + render() { + return ( +
    + +

    Current Item Count: {this.state.itemCount}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/change-inline-css-conditionally-based-on-component-state.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/change-inline-css-conditionally-based-on-component-state.spanish.md new file mode 100644 index 0000000000..4dbaa947c0 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/change-inline-css-conditionally-based-on-component-state.spanish.md @@ -0,0 +1,130 @@ +--- +id: 5a24c314108439a4d4036189 +title: Change Inline CSS Conditionally Based on Component State +localeTitle: Cambiar CSS en línea condicionalmente basado en el estado del componente +challengeType: 6 +isRequired: false +--- + +## Description +
    +En este punto, ha visto varias aplicaciones de representación condicional y el uso de estilos en línea. Aquí hay un ejemplo más que combina estos dos temas. También puede representar CSS de forma condicional en función del estado de un componente React. Para hacer esto, verifica una condición, y si esa condición se cumple, modifica el objeto de estilos que está asignado a los elementos JSX en el método de procesamiento. +Es importante entender este paradigma porque es un cambio dramático con respecto al enfoque más tradicional de aplicar estilos mediante la modificación directa de elementos DOM (que es muy común con jQuery, por ejemplo). En ese enfoque, debe realizar un seguimiento de cuándo cambian los elementos y también manejar la manipulación real directamente. Puede ser difícil hacer un seguimiento de los cambios, lo que podría hacer que su UI sea impredecible. Cuando configura un objeto de estilo basado en una condición, describe cómo debe verse la interfaz de usuario en función del estado de la aplicación. Hay un flujo claro de información que solo se mueve en una dirección. Este es el método preferido al escribir aplicaciones con React. +
    + +## Instructions +
    +El editor de código tiene un componente de entrada controlado simple con un borde con estilo. Desea que el estilo de este borde sea rojo si el usuario escribe más de 15 caracteres de texto en el cuadro de entrada. Agregue una condición para verificar esto y, si la condición es válida, establezca el estilo de borde de entrada en 3px solid red . Puedes probarlo ingresando texto en la entrada. +
    + +## Tests +
    + +```yml +tests: + - text: El componente GateKeeper debe representar un elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find("div").length === 1; })(), "The GateKeeper component should render a div element.");' + - text: El componente GateKeeper debe inicializarse con una input clave de estado establecida en una cadena vacía. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.state().input === ""; })(), "The GateKeeper component should be initialized with a state key input set to an empty string.");' + - text: El componente GateKeeper debe representar una etiqueta h3 y una etiqueta de input . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find("h3").length === 1 && mockedComponent.find("input").length === 1; })(), "The GateKeeper component should render an h3 tag and an input tag.");' + - text: La etiqueta de input debe tener inicialmente un estilo de 1px solid black para la propiedad de border . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); return mockedComponent.find("input").props().style.border === "1px solid black"; })(), "The input tag should initially have a style of 1px solid black for the border property.");' + - text: La etiqueta de input debe tener un estilo con un borde de 3px solid red si el valor de entrada en el estado es más largo que 15 caracteres. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(GateKeeper)); const simulateChange = (el, value) => el.simulate("change", {target: {value}}); let initialStyle = mockedComponent.find("input").props().style.border; const state_1 = () => { mockedComponent.setState({input: "this is 15 char" }); return waitForIt(() => mockedComponent.find("input").props().style.border )}; const state_2 = () => { mockedComponent.setState({input: "A very long string longer than 15 characters." }); return waitForIt(() => mockedComponent.find("input").props().style.border )}; const style_1 = await state_1(); const style_2 = await state_2(); assert(initialStyle === "1px solid black" && style_1 === "1px solid black" && style_2 === "3px solid red", "The input tag should be styled with a border of 3px solid red if the input value in state is longer than 15 characters."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +class GateKeeper extends React.Component { + constructor(props) { + super(props); + this.state = { + input: " + }; + this.handleChange = this.handleChange.bind(this); + } + handleChange(event) { + this.setState({ input: event.target.value }) + } + render() { + let inputStyle = { + border: '1px solid black' + }; + // change code below this line + + // change code above this line + return ( +
    +

    Don't Type Too Much:

    + +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class GateKeeper extends React.Component { + constructor(props) { + super(props); + this.state = { + input: " + }; + this.handleChange = this.handleChange.bind(this); + } + handleChange(event) { + this.setState({ input: event.target.value }) + } + render() { + let inputStyle = { + border: '1px solid black' + }; + if (this.state.input.length > 15) { + inputStyle.border = '3px solid red'; + }; + return ( +
    +

    Don't Type Too Much:

    + +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/compose-react-components.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/compose-react-components.spanish.md new file mode 100644 index 0000000000..6b7d663f2d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/compose-react-components.spanish.md @@ -0,0 +1,183 @@ +--- +id: 5a24c314108439a4d4036166 +title: Compose React Components +localeTitle: Componer React Componentes +challengeType: 6 +isRequired: false +--- + +## Description +
    +A medida que los desafíos continúan usando composiciones más complejas con los componentes React y JSX, hay un punto importante a tener en cuenta. La representación de los componentes de la clase de estilo ES6 dentro de otros componentes no es diferente de la representación de los componentes simples que usó en los últimos desafíos. Puede representar elementos JSX, componentes funcionales sin estado y componentes de clase ES6 dentro de otros componentes. +
    + +## Instructions +
    +En el editor de código, el componente TypesOfFood ya está representando un componente llamado Vegetables . Además, está el componente Fruits del último desafío. +Anide dos componentes dentro de Fruits : primero NonCitrus y luego Citrus . Ambos componentes se proporcionan para usted en el fondo. A continuación, anide el componente de la clase Fruits en el componente TypesOfFood , debajo del encabezado h1 y encima de Vegetables . El resultado debe ser una serie de componentes anidados, que utiliza dos tipos de componentes diferentes. +
    + +## Tests +
    + +```yml +tests: + - text: El componente TypesOfFood debe devolver un único elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === "div"; })(), "The TypesOfFood component should return a single div element.");' + - text: El componente TypesOfFood debe devolver el componente Fruits . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === "Fruits"; })(), "The TypesOfFood component should return the Fruits component.");' + - text: El componente Fruits debe devolver el componente NonCitrus y el componente Citrus . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return (mockedComponent.find("Fruits").children().find("NonCitrus").length === 1 && mockedComponent.find("Fruits").children().find("Citrus").length === 1); })(), "The Fruits component should return the NonCitrus component and the Citrus component.");' + - text: El componente TypesOfFood debe devolver el componente Vegetables debajo del componente Fruits . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === "Vegetables"; })(), "The TypesOfFood component should return the Vegetables component below the Fruits component.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class Fruits extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Fruits:

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; + +class TypesOfFood extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Types of Food:

    + { /* change code below this line */ } + + { /* change code above this line */ } + +
    + ); + } +}; +``` + +
    + +### Before Test +
    + +```jsx +class NonCitrus extends React.Component { + render() { + return ( +
    +

    Non-Citrus:

    +
      +
    • Apples
    • +
    • Blueberries
    • +
    • Strawberries
    • +
    • Bananas
    • +
    +
    + ); + } +}; +class Citrus extends React.Component { + render() { + return ( +
    +

    Citrus:

    +
      +
    • Lemon
    • +
    • Lime
    • +
    • Orange
    • +
    • Grapefruit
    • +
    +
    + ); + } +}; +class Vegetables extends React.Component { + render() { + return ( +
    +

    Vegetables:

    +
      +
    • Brussel Sprouts
    • +
    • Broccoli
    • +
    • Squash
    • +
    +
    + ); + } +}; +``` + +
    + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class Fruits extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Fruits:

    + { /* change code below this line */ } + + + { /* change code above this line */ } +
    + ) + } +} + +class TypesOfFood extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Types of Food:

    + { /* change code below this line */ } + + { /* change code above this line */ } + +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-complex-jsx-element.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-complex-jsx-element.spanish.md new file mode 100644 index 0000000000..a3e93f795d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-complex-jsx-element.spanish.md @@ -0,0 +1,90 @@ +--- +id: 5a24bbe0dba28a8d3cbd4c5d +title: Create a Complex JSX Element +localeTitle: Crear un elemento JSX complejo +challengeType: 6 +isRequired: false +--- + +## Description +
    +El último desafío fue un ejemplo simple de JSX, pero JSX también puede representar HTML más complejo. +Una cosa importante que se debe saber sobre JSX anidado es que debe devolver un solo elemento. +Este elemento primario envolvería todos los otros niveles de elementos anidados. +Por ejemplo, varios elementos JSX escritos como hermanos sin elemento de envoltorio principal no se transpilarán. +Aquí hay un ejemplo: +Válido JSX: +
    <div>
      <p>Paragraph One</p>
      <p>Paragraph Two</p>
      <p>Paragraph Three</p>
    </div>
    +JSX inválido: +
    <p>Paragraph One</p>
    <p>Paragraph Two</p>
    <p>Paragraph Three</p>
    +
    + +## Instructions +
    +Defina una nueva constante JSX que muestre un div que contenga los siguientes elementos en orden: +Un h1 , una p , y una lista desordenada que contiene tres elementos li . Puede incluir cualquier texto que desee dentro de cada elemento. +Nota: Al representar varios elementos como este, puede envolverlos todos entre paréntesis, pero no es estrictamente necesario. También tenga en cuenta que este desafío utiliza una etiqueta div para envolver todos los elementos secundarios dentro de un único elemento principal. Si elimina el div , el JSX ya no se transpilará. Tenga esto en cuenta, ya que también se aplicará cuando devuelva elementos JSX en los componentes React. +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debe devolver un elemento div . + testString: 'assert(JSX.type === "div", "The constant JSX should return a div element.");' + - text: El div debe contener una etiqueta p como el segundo elemento. + testString: 'assert(JSX.props.children[1].type === "p", "The div should contain a p tag as the second element.");' + - text: El div debe contener una etiqueta ul como el tercer elemento. + testString: 'assert(JSX.props.children[2].type === "ul", "The div should contain a ul tag as the third element.");' + - text: El div debe contener una etiqueta h1 como el primer elemento. + testString: 'assert(JSX.props.children[0].type === "h1", "The div should contain an h1 tag as the first element.");' + - text: La ul debe contener tres elementos li . + testString: 'assert(JSX.props.children[2].props.children.length === 3, "The ul should contain three li elements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +// write your code here + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const JSX = ( +
    +

    Hello JSX!

    +

    Some info

    +
      +
    • An item
    • +
    • Another item
    • +
    • A third item
    • +
    +
    ); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-component-with-composition.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-component-with-composition.spanish.md new file mode 100644 index 0000000000..132c175c25 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-component-with-composition.spanish.md @@ -0,0 +1,115 @@ +--- +id: 5a24c314108439a4d4036164 +title: Create a Component with Composition +localeTitle: Crear un componente con composición +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ahora veremos cómo podemos componer varios componentes de React juntos. Imagina que estás creando una aplicación y has creado tres componentes, una Navbar , un Dashboard y un Footer . +Para componer estos componentes juntos, puede crear un componente primario de la App que muestre cada uno de estos tres componentes como secundarios . Para representar un componente como un elemento secundario en un componente React, incluya el nombre del componente escrito como una etiqueta HTML personalizada en el JSX. Por ejemplo, en el método de render podrías escribir: +
    return (
    <App>
      <Navbar />
      <Dashboard />
      <Footer />
    </App>
    )
    +Cuando React encuentra una etiqueta HTML personalizada que hace referencia a otro componente (un nombre de componente envuelto en < /> como en este ejemplo), representa el marcado para ese componente en la ubicación de la etiqueta. Esto debería ilustrar la relación padre / hijo entre el componente de la App y la Navbar , el Dashboard y el Footer . +
    + +## Instructions +
    +En el editor de código, hay un componente funcional simple llamado ChildComponent y un componente React llamado ParentComponent . Componga los dos juntos renderizando el ChildComponent dentro del ParentComponent . Asegúrese de cerrar la etiqueta ChildComponent con una barra diagonal. +Nota: ChildComponent se define con una función de flecha de ES6 porque esta es una práctica muy común cuando se usa React. Sin embargo, debes saber que esto es solo una función. Si no está familiarizado con la sintaxis de la función de flecha, consulte la sección de JavaScript. +
    + +## Tests +
    + +```yml +tests: + - text: El componente React debe devolver un único elemento div . + testString: 'assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.type() === "div"; })(), "The React component should return a single div element.");' + - text: El componente debe devolver dos elementos anidados. + testString: 'assert((function() { var shallowRender = Enzyme.shallow(React.createElement(ParentComponent)); return shallowRender.children().length === 2; })(), "The component should return two nested elements.");' + - text: El componente debe devolver el ChildComponent como su segundo hijo. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ParentComponent)); return mockedComponent.find("ParentComponent").find("ChildComponent").length === 1; })(), "The component should return the ChildComponent as its second child.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const ChildComponent = () => { + return ( +
    +

    I am the child

    +
    + ); +}; + +class ParentComponent extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    I am the parent

    + { /* change code below this line */ } + + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const ChildComponent = () => { + return ( +
    +

    I am the child

    +
    + ); +}; + +class ParentComponent extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    I am the parent

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-form.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-form.spanish.md new file mode 100644 index 0000000000..9849cbb4b4 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-form.spanish.md @@ -0,0 +1,142 @@ +--- +id: 5a24c314108439a4d4036179 +title: Create a Controlled Form +localeTitle: Crear un formulario controlado +challengeType: 6 +isRequired: false +--- + +## Description +
    +El último desafío demostró que React puede controlar el estado interno de ciertos elementos como input y textarea , lo que los convierte en componentes controlados. Esto se aplica también a otros elementos de formulario, incluido el elemento de form HTML regular. +
    + +## Instructions +
    +El componente MyForm se configura con un form vacío con un controlador de envío. Se llamará al controlador de envío cuando se envíe el formulario. +Hemos añadido un botón que envía el formulario. Puede ver que tiene el type conjunto para submit indica que es el botón que controla el formulario. Agregue el elemento de input en el form y establezca su value y los onChange() como el último desafío. Luego debe completar el método handleSubmit para que establezca la propiedad de estado del componente submit al valor de entrada actual en el state local. +Nota: También debe llamar a event.preventDefault() en el controlador de envío, para evitar el comportamiento de envío de formulario predeterminado que actualizará la página web. +Finalmente, cree una etiqueta h1 después del form que representa el valor de submit del state del componente. Luego puede escribir en el formulario y hacer clic en el botón (o presionar intro), y debería ver su entrada renderizada en la página. +
    + +## Tests +
    + +```yml +tests: + - text: MyForm debería devolver un elemento div que contenga un form y una etiqueta h1 . El formulario debe incluir una input y un button . + testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(MyForm)); return (mockedComponent.find("div").children().find("form").length === 1 && mockedComponent.find("div").children().find("h1").length === 1 && mockedComponent.find("form").children().find("input").length === 1 && mockedComponent.find("form").children().find("button").length === 1) })(), "MyForm should return a div element which contains a form and an h1 tag. The form should include an input and a button.");' + - text: "El estado de MyForm debería inicializarse con las propiedades de input y submit , ambas configuradas como cadenas vacías". + testString: 'assert(Enzyme.mount(React.createElement(MyForm)).state("input") === "" && Enzyme.mount(React.createElement(MyForm)).state("submit") === "", "The state of MyForm should initialize with input and submit properties, both set to empty strings.");' + - text: Escribir el elemento de input debe actualizar la propiedad de input del estado del componente. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); return waitForIt(() => mockedComponent.state("input"))}; const _2 = () => { mockedComponent.find("input").simulate("change", { target: { value: "TestInput" }}); return waitForIt(() => ({ state: mockedComponent.state("input"), inputVal: mockedComponent.find("input").props().value }))}; const before = await _1(); const after = await _2(); assert(before === "" && after.state === "TestInput" && after.inputVal === "TestInput", "Typing in the input element should update the input property of the component's state."); }; ' + - text: El envío del formulario debe ejecutar handleSubmit que debe establecer la propiedad de submit en un estado igual a la entrada actual. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); mockedComponent.setState({submit: ""}); mockedComponent.find("input").simulate("change", {target: {value: "SubmitInput"}}); return waitForIt(() => mockedComponent.state("submit"))}; const _2 = () => { mockedComponent.find("form").simulate("submit"); return waitForIt(() => mockedComponent.state("submit"))}; const before = await _1(); const after = await _2(); assert(before === "" && after === "SubmitInput", "Submitting the form should run handleSubmit which should set the submit property in state equal to the current input."); };' + - text: El encabezado h1 debe representar el valor del campo de submit desde el estado del componente. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyForm)); const _1 = () => { mockedComponent.setState({ input: "" }); mockedComponent.setState({submit: ""}); mockedComponent.find("input").simulate("change", {target: {value: "TestInput"}}); return waitForIt(() => mockedComponent.find("h1").text())}; const _2 = () => { mockedComponent.find("form").simulate("submit"); return waitForIt(() => mockedComponent.find("h1").text())}; const before = await _1(); const after = await _2(); assert(before === "" && after === "TestInput", "The h1 header should render the value of the submit field from the component's state."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyForm extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + submit: " + }; + this.handleChange = this.handleChange.bind(this); + this.handleSubmit = this.handleSubmit.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + handleSubmit(event) { + // change code below this line + + // change code above this line + } + render() { + return ( +
    +
    + { /* change code below this line */ } + + { /* change code above this line */ } + +
    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyForm extends React.Component { + constructor(props) { + super(props); + this.state = { + input: ", + submit: " + }; + this.handleChange = this.handleChange.bind(this); + this.handleSubmit = this.handleSubmit.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + handleSubmit(event) { + event.preventDefault() + this.setState({ + submit: this.state.input + }); + } + render() { + return ( +
    +
    + + +
    +

    {this.state.submit}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-input.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-input.spanish.md new file mode 100644 index 0000000000..ba06dd8488 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-controlled-input.spanish.md @@ -0,0 +1,119 @@ +--- +id: 5a24c314108439a4d4036178 +title: Create a Controlled Input +localeTitle: Crear una entrada controlada +challengeType: 6 +isRequired: false +--- + +## Description +
    +Su aplicación puede tener interacciones más complejas entre el state y la interfaz de usuario renderizada. Por ejemplo, los elementos de control de formulario para la entrada de texto, como input y textarea , mantienen su propio estado en el DOM según el tipo de usuario. Con Reaccionar, puede moverse en este estado mutable de un componente Reaccionar state . La entrada del usuario se convierte en parte del state de la aplicación, por lo que React controla el valor de ese campo de entrada. Normalmente, si tiene componentes React con campos de entrada en los que el usuario puede escribir, será un formulario de entrada controlado. +
    + +## Instructions +
    +El editor de código tiene el esqueleto de un componente llamado ControlledInput para crear un elemento de input controlado. El state del componente ya está inicializado con una propiedad de input que contiene una cadena vacía. Este valor representa el texto que un usuario escribe en el campo de input . +Primero, cree un método llamado handleChange() que tenga un parámetro llamado event . Cuando se llama al método, recibe un objeto de event que contiene una cadena de texto del elemento de input . Puede acceder a esta cadena con event.target.value dentro del método. Actualice la propiedad de input del state del componente con esta nueva cadena. +En el método de procesamiento, cree el elemento de input sobre la etiqueta h4 . Agregue un atributo de value que sea igual a la propiedad de input del state del componente. A continuación, añadir un onChange() controlador de eventos se establece en el handleChange() método. +Al escribir en el cuadro de entrada, el texto se procesa mediante el método handleChange() , se establece como la propiedad de input en el state local y se representa como el valor en el cuadro de input en la página. El state componente es la única fuente de verdad con respecto a los datos de entrada. +último, pero no menos importante, no olvide agregar los enlaces necesarios en el constructor. +
    + +## Tests +
    + +```yml +tests: + - text: ControlledInput debe devolver un elemento div que contiene una input y una etiqueta p . + testString: 'assert(Enzyme.mount(React.createElement(ControlledInput)).find("div").children().find("input").length === 1 && Enzyme.mount(React.createElement(ControlledInput)).find("div").children().find("p").length === 1, "ControlledInput should return a div element which contains an input and a p tag.");' + - text: El estado de ControlledInput debe inicializarse con una propiedad de input establecida en una cadena vacía. + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(ControlledInput)).state("input"), "", "The state of ControlledInput should initialize with an input property set to an empty string.");' + - text: 'Al escribir el elemento de entrada, se debe actualizar el estado y el valor de la entrada, y el elemento p debe representar este estado a medida que se escribe.' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(ControlledInput)); const _1 = () => { mockedComponent.setState({ input: "" }); return waitForIt(() => mockedComponent.state("input"))}; const _2 = () => { mockedComponent.find("input").simulate("change", { target: { value: "TestInput" }}); return waitForIt(() => ({ state: mockedComponent.state("input"), text: mockedComponent.find("p").text(), inputVal: mockedComponent.find("input").props().value }))}; const before = await _1(); const after = await _2(); assert(before === "" && after.state === "TestInput" && after.text === "TestInput" && after.inputVal === "TestInput", "Typing in the input element should update the state and the value of the input, and the p element should render this state as you type."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class ControlledInput extends React.Component { + constructor(props) { + super(props); + this.state = { + input: " + }; + // change code below this line + + // change code above this line + } + // change code below this line + + // change code above this line + render() { + return ( +
    + { /* change code below this line */} + + { /* change code above this line */} +

    Controlled Input:

    +

    {this.state.input}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class ControlledInput extends React.Component { + constructor(props) { + super(props); + this.state = { + input: " + }; + this.handleChange = this.handleChange.bind(this); + } + handleChange(event) { + this.setState({ + input: event.target.value + }); + } + render() { + return ( +
    + +

    Controlled Input:

    + +

    {this.state.input}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-react-component.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-react-component.spanish.md new file mode 100644 index 0000000000..25f9e3b295 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-react-component.spanish.md @@ -0,0 +1,94 @@ +--- +id: 5a24c314108439a4d4036163 +title: Create a React Component +localeTitle: Crear un componente React +challengeType: 6 +isRequired: false +--- + +## Description +
    +La otra forma de definir un componente React es con la sintaxis de class ES6. En el siguiente ejemplo, Kitten extiende React.Component : +
    class Kitten extends React.Component {
      constructor(props) {
        super(props);
      }

      render() {
        return (
          <h1>Hi</h1>
        );
      }
    }
    +Esto crea un Kitten clase ES6 que extiende la clase React.Component . Por lo tanto, la clase Kitten ahora tiene acceso a muchas características útiles de React, como los enlaces locales de estado y ciclo de vida. No se preocupe si aún no está familiarizado con estos términos, se cubrirán con mayor detalle en los desafíos posteriores. +También note que la clase Kitten tiene un constructor definido dentro de él que llama a super() . Utiliza super() para llamar al constructor de la clase padre, en este caso React.Component . El constructor es un método especial utilizado durante la inicialización de objetos que se crean con la palabra clave de class . Es una práctica recomendada llamar al constructor un componente con super y pasarle props a ambos. Esto asegura que el componente se inicialice correctamente. Por ahora, sepa que es estándar que se incluya este código. Pronto verás otros usos para el constructor, así como props . +
    + +## Instructions +
    +MyComponent se define en el editor de código usando la sintaxis de clase. Termine de escribir el método de render para que devuelva un elemento div que contenga un h1 con el texto Hello React! . +
    + +## Tests +
    + +```yml +tests: + - text: El componente React debe devolver un elemento div . + testString: 'assert(Enzyme.shallow(React.createElement(MyComponent)).type() === "div", "The React component should return a div element.");' + - text: El div devuelto debe representar un encabezado h1 dentro de él. + testString: 'assert(/

    .*<\/h1><\/div>/.test(Enzyme.shallow(React.createElement(MyComponent)).html()), "The returned div should render an h1 header within it.");' + - text: El encabezado h1 debe contener la cadena Hello React! . + testString: 'assert(Enzyme.shallow(React.createElement(MyComponent)).html() === "

    Hello React!

    ", "The h1 header should contain the string Hello React!.");' + +``` + +

    + +## Challenge Seed +
    + +
    + +```jsx + +class MyComponent extends React.Component { + constructor(props) { + super(props); + } + render() { + // change code below this line + + + + // change code above this line + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + } + render() { + // change code below this line + return ( +
    +

    Hello React!

    +
    + ); + // change code above this line + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-simple-jsx-element.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-simple-jsx-element.spanish.md new file mode 100644 index 0000000000..d6c81c172a --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-simple-jsx-element.spanish.md @@ -0,0 +1,70 @@ +--- +id: 587d7dbc367417b2b2512bb1 +title: Create a Simple JSX Element +localeTitle: Crear un elemento JSX simple +challengeType: 6 +isRequired: false +--- + +## Description +
    +Introducción: React es una biblioteca de vista de código abierto creada y mantenida por Facebook. Es una gran herramienta para representar la interfaz de usuario (UI) de las aplicaciones web modernas. +React utiliza una extensión de sintaxis de JavaScript llamada JSX que le permite escribir HTML directamente dentro de JavaScript. Esto tiene varios beneficios. Le permite usar todo el poder programático de JavaScript dentro de HTML y ayuda a mantener su código legible. En su mayor parte, JSX es similar al HTML que ya ha aprendido, sin embargo, hay algunas diferencias clave que se cubrirán a lo largo de estos desafíos. +Por ejemplo, como JSX es una extensión sintáctica de JavaScript, en realidad puede escribir JavaScript directamente dentro de JSX. Para hacer esto, simplemente incluya el código que desea que sea tratado como JavaScript entre llaves: { 'this is treated as JavaScript code' } . Tenga esto en cuenta, ya que se utiliza en varios desafíos futuros. +Sin embargo, como JSX no es un JavaScript válido, el código JSX debe compilarse en JavaScript. El transpiler Babel es una herramienta popular para este proceso. Para su comodidad, ya se ha agregado entre bastidores para estos desafíos. Si escribes JSX sintácticamente no válido, verás que la primera prueba en estos desafíos falla. +Vale la pena señalar que, bajo el capó, los desafíos se denominan ReactDOM.render(JSX, document.getElementById('root')) . Esta llamada a la función es lo que coloca a su JSX en la representación liviana del DOM de React. React luego utiliza las instantáneas de su propio DOM para optimizar la actualización de solo partes específicas del DOM real. +
    + +## Instructions +
    +Instrucciones: El código actual utiliza JSX para asignar un elemento div a la constante JSX . Reemplaza el div con un elemento h1 y agrega el texto Hello JSX! dentro de eso. +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debería devolver un elemento h1 . + testString: 'assert(JSX.type === "h1", "The constant JSX should return an h1 element.");' + - text: La etiqueta h1 debe incluir el texto Hello JSX! + testString: 'assert(Enzyme.shallow(JSX).contains("Hello JSX!"), "The h1 tag should include the text Hello JSX!");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +const JSX =
    ; + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const JSX =

    Hello JSX!

    ; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateful-component.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateful-component.spanish.md new file mode 100644 index 0000000000..544b00a967 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateful-component.spanish.md @@ -0,0 +1,99 @@ +--- +id: 5a24c314108439a4d4036170 +title: Create a Stateful Component +localeTitle: Crear un componente de estado +challengeType: 6 +isRequired: false +--- + +## Description +
    +Uno de los temas más importantes en React es el state . El estado consiste en cualquier información que su aplicación necesite conocer, que puede cambiar con el tiempo. Desea que sus aplicaciones respondan a los cambios de estado y presenten una interfaz de usuario actualizada cuando sea necesario. React ofrece una buena solución para la administración estatal de aplicaciones web modernas. +Usted crea el estado en un componente React declarando una propiedad de state en la clase del componente en su constructor . Esto inicializa el componente con el state cuando se crea. La propiedad de state debe establecer en un object JavaScript. Declarándolo se ve así: +
    this.state = {
      // describe your state here
    } +You have access to the state object throughout the life of your component. You can update it, render it in your UI, and pass it as props to child components. The state object can be as complex or as simple as you need it to be. Note that you must create a class component by extending React.Component in order to create state like this. +
    + +## Instructions +
    +Hay un componente en el editor de código que intenta representar una propiedad de name de su state . Sin embargo, no hay un state definido. Inicialice el componente con el state en el constructor y asigne su nombre a una propiedad de name . +
    + +## Tests +
    + +```yml +tests: + - text: StatefulComponent debería existir y renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find("StatefulComponent").length === 1; })(), "StatefulComponent should exist and render.");' + - text: StatefulComponent debe representar un elemento div y un elemento h1 . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); return mockedComponent.find("div").length === 1 && mockedComponent.find("h1").length === 1; })(), "StatefulComponent should render a div and an h1 element.");' + - text: El estado de StatefulComponent debe inicializarse con un name propiedad establecido en una cadena. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return ( typeof initialState === "object" && typeof initialState.name === "string"); })(), "The state of StatefulComponent should be initialized with a property name set to a string.");' + - text: El name de la propiedad en el estado de StatefulComponent debe representarse en el elemento h1 . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(StatefulComponent)); const initialState = mockedComponent.state(); return mockedComponent.find("h1").text() === initialState.name; })(), "The property name in the state of StatefulComponent should render in the h1 element.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +class StatefulComponent extends React.Component { + constructor(props) { + super(props); + // initialize state here + + } + render() { + return ( +
    +

    {this.state.name}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class StatefulComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'freeCodeCamp!' + } + } + render() { + return ( +
    +

    {this.state.name}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateless-functional-component.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateless-functional-component.spanish.md new file mode 100644 index 0000000000..5998a3ab1c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/create-a-stateless-functional-component.spanish.md @@ -0,0 +1,85 @@ +--- +id: 5a24c314108439a4d4036162 +title: Create a Stateless Functional Component +localeTitle: Crear un componente funcional sin estado +challengeType: 6 +isRequired: false +--- + +## Description +
    +componentes son el núcleo de React. Todo en React es un componente y aquí aprenderás cómo crear uno. +Hay dos formas de crear un componente React. La primera forma es usar una función de JavaScript. La definición de un componente de esta manera crea un componente funcional sin estado . El concepto de estado en una aplicación será cubierto en desafíos posteriores. Por ahora, piense en un componente sin estado como uno que puede recibir datos y procesarlos, pero no administra ni rastrea los cambios en esos datos. (Cubriremos la segunda forma de crear un componente React en el próximo desafío). +Para crear un componente con una función, simplemente escriba una función de JavaScript que devuelva JSX o null . Una cosa importante a tener en cuenta es que React requiere que el nombre de su función comience con una letra mayúscula. Aquí hay un ejemplo de un componente funcional sin estado que asigna una clase HTML en JSX: +
    // After being transpiled, the <div> will have a CSS class of 'customClass'
    const DemoComponent = function() {
      return (
        <div className='customClass' />
      );
    };
    +Debido a que un componente JSX representa HTML, puede juntar varios componentes para crear una página HTML más compleja. Esta es una de las ventajas clave de la arquitectura de componentes que proporciona React. Le permite componer su IU a partir de muchos componentes separados y aislados. Esto facilita la creación y el mantenimiento de interfaces de usuario complejas. +
    + +## Instructions +
    +El editor de código tiene una función llamada MyComponent . Complete esta función para que devuelva un único elemento div que contenga alguna cadena de texto. +Nota: El texto se considera un elemento secundario del elemento div , por lo que no podrá utilizar una etiqueta de cierre automático. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debe devolver JSX. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.length === 1; })(), "MyComponent should return JSX.");' + - text: MyComponent debería devolver un elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.children().type() === "div" })(), "MyComponent should return a div element.");' + - text: El elemento div debe contener una cadena de texto. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("div").text() !== ""; })(), "The div element should contain a string of text.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const MyComponent = function() { + // change code below this line + + + + // change code above this line +} +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const MyComponent = function() { + // change code below this line + return ( +
    + Demo Solution +
    + ); + // change code above this line +} +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/define-an-html-class-in-jsx.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/define-an-html-class-in-jsx.spanish.md new file mode 100644 index 0000000000..9e4d9c6d43 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/define-an-html-class-in-jsx.spanish.md @@ -0,0 +1,74 @@ +--- +id: 5a24c314108439a4d4036160 +title: Define an HTML Class in JSX +localeTitle: Definir una clase de HTML en JSX +challengeType: 6 +isRequired: false +--- + +## Description +
    +Ahora que se está sintiendo cómodo escribiendo JSX, puede que se esté preguntando en qué se diferencia del HTML. +Hasta ahora, puede parecer que HTML y JSX son exactamente iguales. +Una diferencia clave en JSX es que ya no se puede usar la class palabra para definir clases de HTML. Esto es porque la class es una palabra reservada en JavaScript. En su lugar, JSX utiliza className . +De hecho, la convención de nomenclatura para todos los atributos HTML y referencias de eventos en JSX se convierte en camelCase. Por ejemplo, un evento de clic en JSX es onClick , en lugar de onclick . Del mismo modo, onchange convierte en onChange . Si bien esta es una diferencia sutil, es importante tener en cuenta seguir avanzando. +
    + +## Instructions +
    +Aplique una clase de myDiv al div provisto en el código JSX. +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debe devolver un elemento div . + testString: 'assert.strictEqual(JSX.type, "div", "The constant JSX should return a div element.");' + - text: El div tiene una clase de myDiv . + testString: 'assert.strictEqual(JSX.props.className, "myDiv", "The div has a class of myDiv.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const JSX = ( +
    +

    Add a class to this div

    +
    +); +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const JSX = ( +
    +

    Add a class to this div

    +
    ); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/give-sibling-elements-a-unique-key-attribute.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/give-sibling-elements-a-unique-key-attribute.spanish.md new file mode 100644 index 0000000000..449fe5ba85 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/give-sibling-elements-a-unique-key-attribute.spanish.md @@ -0,0 +1,112 @@ +--- +id: 5a24c314108439a4d403618b +title: Give Sibling Elements a Unique Key Attribute +localeTitle: Dar a los elementos hermanos un atributo clave único +challengeType: 6 +isRequired: false +--- + +## Description +
    +El último desafío mostró cómo se usa el método de map para generar dinámicamente una serie de elementos basados ​​en la entrada del usuario. Sin embargo, faltaba una pieza importante en ese ejemplo. Cuando crea una matriz de elementos, cada uno necesita un atributo de key establecido en un valor único. React utiliza estas teclas para realizar un seguimiento de los elementos que se agregan, cambian o eliminan. Esto ayuda a hacer que el proceso de representación sea más eficiente cuando la lista se modifica de alguna manera. Tenga en cuenta que las claves solo tienen que ser únicas entre elementos hermanos, no tienen que ser únicas a nivel mundial en su aplicación. +
    + +## Instructions +
    +El editor de código tiene una matriz con algunos marcos front-end y un componente funcional sin estado llamado Frameworks() . Frameworks() necesita asignar la matriz a una lista desordenada, como en el último desafío. Termine de escribir la devolución de llamada del map para devolver un elemento li para cada marco en la matriz frontEndFrameworks . Esta vez, asegúrese de dar a cada li un atributo key , establecido en un valor único. +Normalmente, desea que la clave sea algo que identifique de forma única el elemento que se está representando. Como último recurso, se puede usar el índice de matriz, pero normalmente debe intentar usar una identificación única. +
    + +## Tests +
    + +```yml +tests: + - text: El componente Frameworks debería existir y renderizarse a la página. + testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("Frameworks").length === 1, "The Frameworks component should exist and render to the page.");' + - text: Frameworks deberían representar un elemento h1 . + testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("h1").length === 1, "Frameworks should render an h1 element.");' + - text: Frameworks deberían representar un elemento ul . + testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("ul").length === 1, "Frameworks should render a ul element.");' + - text: La etiqueta ul debe mostrar 6 elementos li secundarios. + testString: 'assert(Enzyme.mount(React.createElement(Frameworks)).find("ul").children().length === 6 && Enzyme.mount(React.createElement(Frameworks)).find("ul").childAt(0).name() === "li" && Enzyme.mount(React.createElement(Frameworks)).find("li").length === 6, "The ul tag should render 6 child li elements.");' + - text: Cada elemento del elemento de la lista debe tener un atributo de key único. + testString: 'assert((() => { const ul = Enzyme.mount(React.createElement(Frameworks)).find("ul"); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key(), ul.childAt(4).key(), ul.childAt(5).key(), ]); return keys.size === 6; })(), "Each list item element should have a unique key attribute.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +const frontEndFrameworks = [ + 'React', + 'Angular', + 'Ember', + 'Knockout', + 'Backbone', + 'Vue' +]; + +function Frameworks() { + const renderFrameworks = null; // change code here + return ( +
    +

    Popular Front End JavaScript Frameworks

    +
      + {renderFrameworks} +
    +
    + ); +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const frontEndFrameworks = [ + 'React', + 'Angular', + 'Ember', + 'Knockout', + 'Backbone', + 'Vue' +]; + +function Frameworks() { + const renderFrameworks = frontEndFrameworks.map((fw, i) => { + return
  • {fw}
  • + }) + return ( +
    +

    Popular Front End JavaScript Frameworks

    +
      + {renderFrameworks} +
    +
    + ); +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/introducing-inline-styles.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/introducing-inline-styles.spanish.md new file mode 100644 index 0000000000..0720703052 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/introducing-inline-styles.spanish.md @@ -0,0 +1,88 @@ +--- +id: 5a24c314108439a4d4036181 +title: Introducing Inline Styles +localeTitle: Introducción a los estilos en línea +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hay otros conceptos complejos que agregan capacidades poderosas a su código React. Pero puede que se esté preguntando sobre el problema más simple de cómo diseñar los elementos JSX que crea en React. Probablemente sepa que no será exactamente lo mismo que trabajar con HTML debido a la forma en que aplica las clases a los elementos JSX . +Si importa estilos de una hoja de estilo, no es muy diferente en absoluto. Aplicas una clase a tu elemento JSX usando el atributo className y aplicas estilos a la clase en tu hoja de estilo. Otra opción es aplicar estilos en línea , que son muy comunes en el desarrollo de ReactJS. +Aplicas estilos en línea a elementos JSX similares a cómo lo haces en HTML, pero con algunas diferencias JSX. Aquí hay un ejemplo de un estilo en línea en HTML: +<div style="color: yellow; font-size: 16px">Mellow Yellow</div> +elementos JSX usan el atributo de style , pero debido a la forma en que se transpila JSX, no se puede establecer el valor en una string . En su lugar, lo establece igual a un object JavaScript. Aquí hay un ejemplo: +<div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div> +¿Observa cómo camelCase la propiedad "fontSize"? Esto se debe a que React no aceptará claves de kebab en el objeto de estilo. React aplicará el nombre de propiedad correcto para nosotros en el HTML. +
    + +## Instructions +
    +Agregue un atributo de style al div en el editor de código para darle al texto un color rojo y un tamaño de fuente de 72px. +Tenga en cuenta que, opcionalmente, puede configurar el tamaño de la fuente como un número, omitiendo las unidades "px", o escribirlo como "72px". +
    + +## Tests +
    + +```yml +tests: + - text: El componente debe representar un elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().type() === "div"; })(), "The component should render a div element.");' + - text: El elemento div debe tener un color red . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return mockedComponent.children().props().style.color === "red"; })(), "The div element should have a color of red.");' + - text: El elemento div debe tener un tamaño de fuente de 72px . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Colorful)); return (mockedComponent.children().props().style.fontSize === 72 || mockedComponent.children().props().style.fontSize === "72" || mockedComponent.children().props().style.fontSize === "72px"); })(), "The div element should have a font size of 72px.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +class Colorful extends React.Component { + render() { + return ( +
    Big Red
    + ); + } +}; + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class Colorful extends React.Component { + render() { + return ( +
    Big Red
    + ); + } +}; + +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/learn-about-self-closing-jsx-tags.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/learn-about-self-closing-jsx-tags.spanish.md new file mode 100644 index 0000000000..86debafc85 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/learn-about-self-closing-jsx-tags.spanish.md @@ -0,0 +1,87 @@ +--- +id: 5a24c314108439a4d4036161 +title: Learn About Self-Closing JSX Tags +localeTitle: Aprenda acerca de las etiquetas JSX de cierre automático +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hasta ahora, ha visto cómo JSX se diferencia de HTML en una forma clave con el uso de className vs. class para definir clases de HTML. +Otra forma importante en que JSX difiere de HTML es en la idea de la etiqueta de cierre automático. +En HTML, casi todas las etiquetas tienen una etiqueta de apertura y de cierre: <div></div> ; La etiqueta de cierre siempre tiene una barra diagonal hacia delante antes del nombre de la etiqueta que está cerrando. Sin embargo, hay instancias especiales en HTML llamadas "etiquetas de cierre automático", o etiquetas que no requieren una etiqueta de apertura y de cierre antes de que pueda comenzar otra etiqueta. +Por ejemplo, la etiqueta de salto de línea puede escribirse como <br> o como <br /> , pero nunca debe escribirse como <br></br> , ya que no contiene ningún contenido. +En JSX, las reglas son un poco diferentes. Cualquier elemento JSX puede escribirse con una etiqueta de cierre automático, y cada elemento debe estar cerrado. La etiqueta de salto de línea, por ejemplo, siempre debe escribirse como <br /> para que sea un JSX válido que pueda ser transpilado. Un <div> , por otro lado, puede escribirse como <div /> o <div></div> . La diferencia es que en la primera versión de sintaxis no hay forma de incluir nada en <div /> . Verá en los desafíos posteriores que esta sintaxis es útil al procesar componentes React. +
    + +## Instructions +
    +Arregle los errores en el editor de código para que JSX sea válido y se realice correctamente. Asegúrese de no cambiar ninguno de los contenidos, solo necesita cerrar las etiquetas donde se necesiten. +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debe devolver un elemento div . + testString: 'assert.strictEqual(JSX.type, "div", "The constant JSX should return a div element.");' + - text: El div debe contener una etiqueta br . + testString: 'assert(Enzyme.shallow(JSX).find("br").length === 1, "The div should contain a br tag.");' + - text: El div debe contener una etiqueta hr . + testString: 'assert(Enzyme.shallow(JSX).find("hr").length === 1, "The div should contain an hr tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const JSX = ( +
    + {/* remove comment and change code below this line +

    Welcome to React!


    +

    Be sure to close all tags!

    +
    + remove comment and change code above this line */} +
    +); + +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const JSX = ( +
    + {/* change code below this line */} +

    Welcome to React!


    +

    Be sure to close all tags!

    +
    + {/* change code above this line */} +
    +); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/manage-updates-with-lifecycle-methods.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/manage-updates-with-lifecycle-methods.spanish.md new file mode 100644 index 0000000000..05320514ac --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/manage-updates-with-lifecycle-methods.spanish.md @@ -0,0 +1,148 @@ +--- +id: 5a24c314108439a4d403617f +title: Manage Updates with Lifecycle Methods +localeTitle: Gestionar actualizaciones con métodos de ciclo de vida +challengeType: 6 +isRequired: false +--- + +## Description +
    +Otro método de ciclo de vida es componentWillReceiveProps() que se llama cada vez que un componente recibe nuevos accesorios. Este método recibe las nuevas propuestas como un argumento, que generalmente se escribe como nextProps . Puede usar este argumento y comparar con this.props y realizar acciones antes de que se actualice el componente. Por ejemplo, puede llamar a setState() localmente antes de que se procese la actualización. +Otro método es componentDidUpdate() , y se llama inmediatamente después de que un componente vuelve a renderizarse. Tenga en cuenta que la representación y el montaje se consideran cosas diferentes en el ciclo de vida del componente. Cuando se carga una página por primera vez, todos los componentes se montan y aquí es donde se llaman los métodos, por ejemplo, componentWillMount() y componentDidMount() . Después de esto, a medida que cambia el estado, los componentes se vuelven a representar. El próximo reto lo cubre con más detalle. +
    + +## Instructions +
    +El cuadro de Dialog componente secundario recibe message de texto de su elemento principal, el componente Controller . Escriba el método componentWillReceiveProps() en el componente Dialog y this.props que registre this.props y nextProps en la consola. Deberá pasar nextProps como un argumento a este método y, aunque es posible nombrarlo de alguna manera, nextProps nombre nextProps aquí. +A continuación, agregue componentDidUpdate() en el componente de Dialog , y registre una declaración que indique que el componente se ha actualizado. Este método funciona de manera similar a componentWillUpdate() , que se proporciona para usted. Ahora haga clic en el botón para cambiar el mensaje y ver la consola de su navegador. El orden de las sentencias de la consola muestra el orden en que se llaman los métodos. +Nota: Deberá escribir los métodos del ciclo de vida como funciones normales y no como funciones de flecha para pasar las pruebas (tampoco hay ninguna ventaja al escribir métodos de ciclo de vida como funciones de flecha). +
    + +## Tests +
    + +```yml +tests: + - text: El componente Controller debe representar el componente Dialog como un elemento secundario. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("Dialog").length === 1; })(), "The Controller component should render the Dialog component as a child.");' + - text: El método componentWillReceiveProps en el componente Dialog debe registrar this.props en la consola. + testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,""); return lifecycleChild.includes("console.log") && lifecycleChild.includes("this.props") })(), "The componentWillReceiveProps method in the Dialog component should log this.props to the console.");' + - text: El método componentWillReceiveProps en el componente Dialog debe registrar nextProps en la consola. + testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentWillReceiveProps.toString().replace(/ /g,""); const nextPropsAsParameterTest = /componentWillReceiveProps(| *?= *?)(\(|)nextProps(\)|)( *?=> *?{| *?{|{)/; const nextPropsInConsoleLogTest = /console\.log\(.*?nextProps\b.*?\)/; return ( lifecycleChild.includes("console.log") && nextPropsInConsoleLogTest.test(lifecycleChild) && nextPropsAsParameterTest.test(lifecycleChild) ); })(), "The componentWillReceiveProps method in the Dialog component should log nextProps to the console.");' + - text: El componente Dialog debe llamar al método componentDidUpdate y registrar un mensaje en la consola. + testString: 'assert((function() { const lifecycleChild = React.createElement(Dialog).type.prototype.componentDidUpdate.toString().replace(/ /g,""); return lifecycleChild.length !== "undefined" && lifecycleChild.includes("console.log"); })(), "The Dialog component should call the componentDidUpdate method and log a message to the console.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class Dialog extends React.Component { + constructor(props) { + super(props); + } + componentWillUpdate() { + console.log('Component is about to update...'); + } + // change code below this line + + // change code above this line + render() { + return

    {this.props.message}

    + } +}; + +class Controller extends React.Component { + constructor(props) { + super(props); + this.state = { + message: 'First Message' + }; + this.changeMessage = this.changeMessage.bind(this); + } + changeMessage() { + this.setState({ + message: 'Second Message' + }); + } + render() { + return ( +
    + + +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class Dialog extends React.Component { + constructor(props) { + super(props); + } + componentWillUpdate() { + console.log('Component is about to update...'); + } + // change code below this line + componentWillReceiveProps(nextProps) { + console.log(this.props, nextProps); + } + componentDidUpdate() { + console.log('Component re-rendered'); + } + // change code above this line + render() { + return

    {this.props.message}

    + } +}; + +class Controller extends React.Component { + constructor(props) { + super(props); + this.state = { + message: 'First Message' + }; + this.changeMessage = this.changeMessage.bind(this); + } + changeMessage() { + this.setState({ + message: 'Second Message' + }); + } + render() { + return ( +
    + + +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/optimize-re-renders-with-shouldcomponentupdate.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/optimize-re-renders-with-shouldcomponentupdate.spanish.md new file mode 100644 index 0000000000..08e6294fb8 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/optimize-re-renders-with-shouldcomponentupdate.spanish.md @@ -0,0 +1,153 @@ +--- +id: 5a24c314108439a4d4036180 +title: Optimize Re-Renders with shouldComponentUpdate +localeTitle: Optimizar Re-Renders con shouldComponentUpdate +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hasta ahora, si algún componente recibe un nuevo state o nuevos props , se vuelve a rendir a sí mismo ya todos sus hijos. Esto suele estar bien. Pero React proporciona un método de ciclo de vida al que puede llamar cuando los componentes secundarios reciben un nuevo state o props , y declaran específicamente si los componentes deberían actualizarse o no. El método es shouldComponentUpdate() , y toma nextProps y nextState como parámetros. +Este método es una forma útil de optimizar el rendimiento. Por ejemplo, el comportamiento predeterminado es que su componente se vuelve a procesar cuando recibe nuevos props , incluso si los props no han cambiado. Puedes usar shouldComponentUpdate() para evitar esto al comparar los props . El método debe devolver un valor boolean que indique a React si actualizar o no el componente. Puede comparar los props actuales ( this.props ) con los props siguientes ( nextProps ) para determinar si necesita actualizar o no, y devolver true o false consecuencia. +
    + +## Instructions +
    +El método shouldComponentUpdate() se agrega en un componente llamado OnlyEvens . Actualmente, este método devuelve true por lo que OnlyEvens vuelve a representar cada vez que recibe nuevos props . Modifique el método para que OnlyEvens solo se actualice si el value de sus nuevos accesorios es par. Haga clic en el botón Add y observe el orden de los eventos en la consola de su navegador a medida que se activan los otros ganchos del ciclo de vida. +
    + +## Tests +
    + +```yml +tests: + - text: El componente Controller debe representar el componente OnlyEvens como un elemento secundario. + testString: 'assert((() => { const mockedComponent = Enzyme.mount(React.createElement(Controller)); return mockedComponent.find("Controller").length === 1 && mockedComponent.find("OnlyEvens").length === 1; })(), "The Controller component should render the OnlyEvens component as a child.");' + - text: El método shouldComponentUpdate debe definirse en el componente OnlyEvens . + testString: 'assert((() => { const child = React.createElement(OnlyEvens).type.prototype.shouldComponentUpdate.toString().replace(/s/g,""); return child !== "undefined"; })(), "The shouldComponentUpdate method should be defined on the OnlyEvens component.");' + - text: El componente OnlyEvens debe devolver una etiqueta h1 que representa el valor de this.props.value . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 1000 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const second = () => { mockedComponent.setState({ value: 10 }); return waitForIt(() => mockedComponent.find("h1").html()); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === "

    1000

    " && secondValue === "

    10

    ", "The OnlyEvens component should return an h1 tag which renders the value of this.props.value."); }; ' + - text: OnlyEvens debería volver a generar solo cuando nextProps.value es par. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(Controller)); const first = () => { mockedComponent.setState({ value: 8 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const second = () => { mockedComponent.setState({ value: 7 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const third = () => { mockedComponent.setState({ value: 42 }); return waitForIt(() => mockedComponent.find("h1").text()); }; const firstValue = await first(); const secondValue = await second(); const thirdValue = await third(); assert(firstValue === "8" && secondValue === "8" && thirdValue === "42", "OnlyEvens should re-render only when nextProps.value is even."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class OnlyEvens extends React.Component { + constructor(props) { + super(props); + } + shouldComponentUpdate(nextProps, nextState) { + console.log('Should I update?'); + // change code below this line + return true; + // change code above this line + } + componentWillReceiveProps(nextProps) { + console.log('Receiving new props...'); + } + componentDidUpdate() { + console.log('Component re-rendered.'); + } + render() { + return

    {this.props.value}

    + } +}; + +class Controller extends React.Component { + constructor(props) { + super(props); + this.state = { + value: 0 + }; + this.addValue = this.addValue.bind(this); + } + addValue() { + this.setState({ + value: this.state.value + 1 + }); + } + render() { + return ( +
    + + +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class OnlyEvens extends React.Component { + constructor(props) { + super(props); + } + shouldComponentUpdate(nextProps, nextState) { + console.log('Should I update?'); + // change code below this line + return nextProps.value % 2 === 0; + // change code above this line + } + componentWillReceiveProps(nextProps) { + console.log('Receiving new props...'); + } + componentDidUpdate() { + console.log('Component re-rendered.'); + } + render() { + return

    {this.props.value}

    + } +}; + +class Controller extends React.Component { + constructor(props) { + super(props); + this.state = { + value: 0 + }; + this.addValue = this.addValue.bind(this); + } + addValue() { + this.setState({ + value: this.state.value + 1 + }); + } + render() { + return ( +
    + + +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/override-default-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/override-default-props.spanish.md new file mode 100644 index 0000000000..49fb436335 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/override-default-props.spanish.md @@ -0,0 +1,101 @@ +--- +id: 5a24c314108439a4d403616c +title: Override Default Props +localeTitle: Anular apoyos predeterminados +challengeType: 6 +isRequired: false +--- + +## Description +
    +La capacidad de establecer accesorios predeterminados es una característica útil en React. La forma de anular los accesorios predeterminados es establecer explícitamente los valores de prop para un componente. +
    + +## Instructions +
    +El componente ShoppingCart ahora representa un componente secundario Items . Este componente de Items tiene una quantity prop predeterminada establecida en el entero 0 . Anule el prop predeterminado al pasar un valor de 10 por quantity . +Nota: recuerde que la sintaxis para agregar una propuesta a un componente es similar a la forma en que agrega atributos HTML. Sin embargo, dado que el valor para la quantity es un número entero, no irá entre comillas, pero debería estar entre corchetes. Por ejemplo, {100} . Esta sintaxis le dice a JSX que interprete el valor entre las llaves directamente como JavaScript. +
    + +## Tests +
    + +```yml +tests: + - text: El componente ShoppingCart debe renderizar. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("ShoppingCart").length === 1; })(), "The component ShoppingCart should render.");' + - text: Los Items componente deben hacer. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("Items").length === 1; })(), "The component Items should render.");' + - text: 'El componente Items debe tener una propiedad de { quantity: 10 } aprobada desde el componente ShoppingCart .' + testString: 'getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart)); return mockedComponent.find("Items").props().quantity == 10 && getUserInput("index").replace(/ /g,"").includes(""); })(), "The Items component should have a prop of { quantity: 10 } passed from the ShoppingCart component.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const Items = (props) => { + return

    Current Quantity of Items in Cart: {props.quantity}

    +} + +Items.defaultProps = { + quantity: 0 +} + +class ShoppingCart extends React.Component { + constructor(props) { + super(props); + } + render() { + { /* change code below this line */ } + return + { /* change code above this line */ } + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const Items = (props) => { + return

    Current Quantity of Items in Cart: {props.quantity}

    +} + +Items.defaultProps = { + quantity: 0 +} + +class ShoppingCart extends React.Component { + constructor(props) { + super(props); + } + render() { + { /* change code below this line */ } + return + { /* change code above this line */ } + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/pass-a-callback-as-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-a-callback-as-props.spanish.md new file mode 100644 index 0000000000..011ab07369 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-a-callback-as-props.spanish.md @@ -0,0 +1,177 @@ +--- +id: 5a24c314108439a4d403617b +title: Pass a Callback as Props +localeTitle: Pasar una devolución de llamada como accesorios +challengeType: 6 +isRequired: false +--- + +## Description +
    +Puede pasar el state como accesorios a componentes secundarios, pero no está limitado a pasar datos. También puede pasar funciones de controlador o cualquier método que esté definido en un componente React a un componente secundario. Así es como permite que los componentes secundarios interactúen con sus componentes principales. Le pasas métodos a un niño como un apoyo regular. Se le asigna un nombre y usted tiene acceso a ese nombre de método en this.props en el componente secundario. +
    + +## Instructions +
    +Hay tres componentes descritos en el editor de código. El MyApp componente es el padre que va a hacer que las GetInput y RenderInput componentes hijos. Añadir el GetInput componente al método render en MyApp , a continuación, pasar un puntal llamada input asignado a inputValue de MyApp 's state . También cree un prop llamado handleChange y pase el manejador de entrada handleChange . +A continuación, agregue RenderInput al método de procesamiento en MyApp , luego cree un prop llamado input y pase el inputValue del state . Una vez que haya terminado, podrá escribir el campo de input en el componente GetInput , que luego invoca el método del controlador en su elemento principal a través de accesorios. Esto actualiza la entrada en el state del padre, que se pasa como apoyo a ambos hijos. Observe cómo los datos fluyen entre los componentes y cómo la única fuente de verdad sigue siendo el state del componente principal. Es cierto que este ejemplo es un poco artificial, pero debería servir para ilustrar cómo los datos y las devoluciones de llamada se pueden pasar entre los componentes React. +
    + +## Tests +
    + +```yml +tests: + - text: El componente MyApp debería renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("MyApp").length === 1; })(), "The MyApp component should render.");' + - text: El componente GetInput debería renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("GetInput").length === 1; })(), "The GetInput component should render.");' + - text: El componente RenderInput debería renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("RenderInput").length === 1; })(), "The RenderInput component should render.");' + - text: El componente GetInput debería recibir la propiedad de estado de MyApp inputValue como props y contener un elemento de input que modifique MyApp estado de MyApp . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: ""}); return waitForIt(() => mockedComponent.state() )}; const state_2 = () => { mockedComponent.find("input").simulate("change", {target: {value: "TestInput"}}); return waitForIt(() => mockedComponent.state() )}; const updated_1 = await state_1(); const updated_2 = await state_2(); assert(updated_1.inputValue === "" && updated_2.inputValue === "TestInput", "The GetInput component should receive the MyApp state property inputValue as props and contain an input element which modifies MyApp state."); }; ' + - text: El componente RenderInput debe recibir la propiedad de estado de MyApp inputValue como props. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const state_1 = () => { mockedComponent.setState({inputValue: "TestName"}); return waitForIt(() => mockedComponent )}; const updated_1 = await state_1(); assert(updated_1.find("p").text().includes("TestName"), "The RenderInput component should receive the MyApp state property inputValue as props."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyApp extends React.Component { + constructor(props) { + super(props); + this.state = { + inputValue: " + } + this.handleChange = this.handleChange.bind(this); + } + handleChange(event) { + this.setState({ + inputValue: event.target.value + }); + } + render() { + return ( +
    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; + +class GetInput extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Get Input:

    + +
    + ); + } +}; + +class RenderInput extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Input Render:

    +

    {this.props.input}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyApp extends React.Component { + constructor(props) { + super(props); + this.state = { + inputValue: " + } + this.handleChange = this.handleChange.bind(this); + } + handleChange(event) { + this.setState({ + inputValue: event.target.value + }); + } + render() { + return ( +
    + + +
    + ); + } +}; + +class GetInput extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Get Input:

    + +
    + ); + } +}; + +class RenderInput extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Input Render:

    +

    {this.props.input}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/pass-an-array-as-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-an-array-as-props.spanish.md new file mode 100644 index 0000000000..ca59305895 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-an-array-as-props.spanish.md @@ -0,0 +1,122 @@ +--- +id: 5a24c314108439a4d403616a +title: Pass an Array as Props +localeTitle: Pasar una matriz como apoyos +challengeType: 6 +isRequired: false +--- + +## Description +
    +El último desafío demostró cómo pasar información de un componente de los padres a un componente secundario como props o propiedades. Este desafío analiza cómo se pueden pasar las matrices como props . Para pasar una matriz a un elemento JSX, se debe tratar como JavaScript y se debe incluir entre llaves. +
    <ParentComponent>
      <ChildComponent colors={["green", "blue", "red"]} />
    </ParentComponent>
    +El componente hijo tiene acceso a los colors propiedad de matriz. Se pueden usar métodos de matriz como join() al acceder a la propiedad. +const ChildComponent = (props) => <p>{props.colors.join(', ')}</p> +Esto unirá todos los elementos de la matriz de colors en una cadena separada por comas y producirá: +<p>green, blue, red</p> +Más adelante, aprenderemos sobre otros métodos comunes para procesar matrices de datos en React. +
    + +## Instructions +
    +Hay componentes List y ToDo en el editor de código. Al representar cada List desde el componente de ToDo , pase una propiedad de tasks asignada a una serie de tareas a realizar, por ejemplo ["walk dog", "workout"] . Luego acceda a esta matriz de tasks en el componente List , mostrando su valor dentro del elemento p . Utilice join(", ") para mostrar la matriz props.tasks en el elemento p como una lista separada por comas. La lista de hoy debe tener al menos 2 tareas y la de mañana debe tener al menos 3 tareas. +
    + +## Tests +
    + +```yml +tests: + - text: El componente ToDo debe devolver un solo div exterior. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().type() === "div"; })(), "The ToDo component should return a single outer div.");' + - text: El tercer elemento secundario del componente ToDo debe ser una instancia del componente List . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(2).name() === "List"; })(), "The third child of the ToDo component should be an instance of the List component.");' + - text: El quinto elemento secundario del componente ToDo debe ser una instancia del componente List . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.children().first().childAt(4).name() === "List"; })(), "The fifth child of the ToDo component should be an instance of the List component.");' + - text: Ambas instancias del componente List deben tener una propiedad llamada tasks y las tasks deben ser de tipo array. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return Array.isArray(mockedComponent.find("List").get(0).props.tasks) && Array.isArray(mockedComponent.find("List").get(1).props.tasks); })(), "Both instances of the List component should have a property called tasks and tasks should be of type array.");' + - text: El primer componente de la List que representa las tareas de hoy debe tener 2 o más elementos. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("List").get(0).props.tasks.length >= 2; })(), "The first List component representing the tasks for today should have 2 or more items.");' + - text: El segundo componente de la List que representa las tareas para mañana debe tener 3 o más elementos. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("List").get(1).props.tasks.length >= 3; })(), "The second List component representing the tasks for tomorrow should have 3 or more items.");' + - text: El componente List debe representar el valor de las tasks prop en la etiqueta p como una lista separada por comas, por ejemplo, walk dog, workout . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(ToDo)); return mockedComponent.find("p").get(0).props.children === mockedComponent.find("List").get(0).props.tasks.join(", ") && mockedComponent.find("p").get(1).props.children === mockedComponent.find("List").get(1).props.tasks.join(", "); })(), "The List component should render the value from the tasks prop in the p tag as a comma separated list, for example walk dog, workout.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const List= (props) => { + { /* change code below this line */ } + return

    {}

    + { /* change code above this line */ } +}; + +class ToDo extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    To Do Lists

    +

    Today

    + { /* change code below this line */ } + +

    Tomorrow

    + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const List= (props) => { + return

    {props.tasks.join(', ')}

    +}; + +class ToDo extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    To Do Lists

    +

    Today

    + +

    Tomorrow

    + +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/pass-props-to-a-stateless-functional-component.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-props-to-a-stateless-functional-component.spanish.md new file mode 100644 index 0000000000..4a1ff4eab5 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-props-to-a-stateless-functional-component.spanish.md @@ -0,0 +1,123 @@ +--- +id: 5a24c314108439a4d4036169 +title: Pass Props to a Stateless Functional Component +localeTitle: Pase los apoyos a un componente funcional sin estado +challengeType: 6 +isRequired: false +--- + +## Description +
    +Los desafíos anteriores cubrieron mucho la creación y composición de elementos JSX, componentes funcionales y componentes de clase de estilo ES6 en React. Con esta base, es hora de ver otra característica muy común en React: props . En React, puede pasar accesorios o propiedades a componentes secundarios. Supongamos que tiene un componente de la App que representa un componente secundario llamado Welcome que es un componente funcional sin estado. Puedes pasar user propiedad de Welcome un user escribiendo: +
    <App>
      <Welcome user='Mark' />
    </App>
    +Utiliza los atributos HTML personalizados que React proporciona soporte para pasar el user la propiedad al componente Welcome . Ya que Welcome es un componente funcional sin estado, tiene acceso a este valor así: +
    const Welcome = (props) => <h1>Hello, {props.user}!</h1>
    +Es estándar llamar a este valor props y cuando se trata de componentes funcionales sin estado, básicamente lo considera como un argumento de una función que devuelve JSX. Puede acceder al valor del argumento en el cuerpo de la función. Con los componentes de clase, verás que esto es un poco diferente. +
    + +## Instructions +
    +Hay componentes de Calendar y CurrentDate en el editor de código. Al representar CurrentDate desde el componente Calendar , pase una propiedad de date asignada a la fecha actual desde el objeto Date de JavaScript. Luego acceda a este prop en el componente CurrentDate , mostrando su valor dentro de las etiquetas p . Tenga en cuenta que para que prop valores prop sean evaluados como JavaScript, deben estar encerrados entre paréntesis, por ejemplo date={Date()} . +
    + +## Tests +
    + +```yml +tests: + - text: El componente Calendar debe devolver un único elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().type() === "div"; })(), "The Calendar component should return a single div element.");' + - text: El segundo elemento secundario del componente Calendar debe ser el componente CurrentDate . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).name() === "CurrentDate"; })(), "The second child of the Calendar component should be the CurrentDate component.");' + - text: El componente CurrentDate debe tener una prop llamada date . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.children().childAt(1).props().date })(), "The CurrentDate component should have a prop called date.");' + - text: La date prop. Del CurrentDate debe contener una cadena de texto. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); const prop = mockedComponent.children().childAt(1).props().date; return( typeof prop === "string" && prop.length > 0 ); })(), "The date prop of the CurrentDate should contain a string of text.");' + - text: El componente CurrentDate debe representar el valor de la date prop en la etiqueta p . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(Calendar)); return mockedComponent.find("p").html().includes(Date().substr(3)); })(), "The CurrentDate component should render the value from the date prop in the p tag.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +const CurrentDate = (props) => { + return ( +
    + { /* change code below this line */ } +

    The current date is:

    + { /* change code above this line */ } +
    + ); +}; + +class Calendar extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    What date is it?

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const CurrentDate = (props) => { + return ( +
    + { /* change code below this line */ } +

    The current date is: {props.date}

    + { /* change code above this line */ } +
    + ); +}; + +class Calendar extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    What date is it?

    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/pass-state-as-props-to-child-components.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-state-as-props-to-child-components.spanish.md new file mode 100644 index 0000000000..2be50e288c --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/pass-state-as-props-to-child-components.spanish.md @@ -0,0 +1,121 @@ +--- +id: 5a24c314108439a4d403617a +title: Pass State as Props to Child Components +localeTitle: Pasar estado como accesorios a componentes secundarios +challengeType: 6 +isRequired: false +--- + +## Description +
    +Vio muchos ejemplos que pasaron apoyos a elementos JSX secundarios y componentes React secundarios en desafíos anteriores. Quizás te preguntes de dónde provienen esos accesorios. Un patrón común es tener un componente con estado que contenga el state importante para su aplicación, que luego presente componentes secundarios. Desea que estos componentes tengan acceso a algunas partes de ese state , que se pasan como accesorios. +Por ejemplo, tal vez tenga un componente de la App que presente una Navbar , entre otros componentes. En su App , tiene un state que contiene mucha información de usuario, pero la Navbar solo necesita acceso al nombre de usuario del usuario para poder mostrarla. Navbar esa pieza de state al componente Navbar como prop. +Este patrón ilustra algunos paradigmas importantes en React. El primero es el flujo de datos unidireccional . El estado fluye en una dirección en el árbol de los componentes de la aplicación, desde el componente primario con estado hasta los componentes secundarios. Los componentes secundarios solo reciben los datos de estado que necesitan. La segunda es que las aplicaciones con estado complejas pueden dividirse en solo unos pocos, o tal vez un solo componente con estado. El resto de sus componentes simplemente reciben el estado del padre como apoyo y representan una IU desde ese estado. Comienza a crear una separación donde la administración del estado se maneja en una parte del código y la representación de la interfaz de usuario en otra. Este principio de separar la lógica de estado de la lógica de UI es uno de los principios clave de React. Cuando se usa correctamente, hace que el diseño de aplicaciones complejas y con estado sea mucho más fácil de administrar. +
    + +## Instructions +
    +El componente MyApp tiene estado y representa un componente de la Navbar como un elemento secundario. Pase la propiedad del name en su state hasta el componente secundario, luego muestre el name en la etiqueta h1 que forma parte del método de renderizado de la Navbar de Navbar . +
    + +## Tests +
    + +```yml +tests: + - text: El componente MyApp debe renderizarse con un componente Navbar dentro. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyApp)); return mockedComponent.find("MyApp").length === 1 && mockedComponent.find("Navbar").length === 1; })(), "The MyApp component should render with a Navbar component inside.");' + - text: El componente Navbar debe recibir el name propiedad de estado MyApp como props. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const setState = () => { mockedComponent.setState({name: "TestName"}); return waitForIt(() => mockedComponent.find("Navbar").props() )}; const navProps = await setState(); assert(navProps.name === "TestName", "The Navbar component should receive the MyApp state property name as props."); }; ' + - text: El elemento h1 en la Navbar de Navbar debe representar el name prop. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyApp)); const navH1Before = mockedComponent.find("Navbar").find("h1").text(); const setState = () => { mockedComponent.setState({name: "TestName"}); return waitForIt(() => mockedComponent.find("Navbar").find("h1").text() )}; const navH1After = await setState(); assert(new RegExp("TestName").test(navH1After) && navH1After !== navH1Before, "The h1 element in Navbar should render the name prop."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyApp extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'CamperBot' + } + } + render() { + return ( +
    + +
    + ); + } +}; + +class Navbar extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Hello, my name is: /* your code here */

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyApp extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'CamperBot' + } + } + render() { + return ( +
    + +
    + ); + } +}; +class Navbar extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Hello, my name is: {this.props.name}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-a-class-component-to-the-dom.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-a-class-component-to-the-dom.spanish.md new file mode 100644 index 0000000000..6dfd8a2e8d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-a-class-component-to-the-dom.spanish.md @@ -0,0 +1,140 @@ +--- +id: 5a24c314108439a4d4036167 +title: Render a Class Component to the DOM +localeTitle: Renderizar un componente de clase al DOM +challengeType: 6 +isRequired: false +--- + +## Description +
    +Es posible que recuerde usar la API ReactDOM en un desafío anterior para representar elementos JSX al DOM. El proceso para renderizar componentes React se verá muy similar. Los últimos desafíos se enfocaron en los componentes y la composición, por lo que el renderizado se realizó para usted entre bastidores. Sin embargo, ninguno de los códigos React que escriba se procesarán en el DOM sin hacer una llamada a la API ReactDOM. +Aquí hay una actualización de la sintaxis: ReactDOM.render(componentToRender, targetNode) . El primer argumento es el componente React que desea procesar. El segundo argumento es el nodo DOM en el que desea procesar ese componente. +componentes de React se pasan a ReactDOM.render() un poco diferente a los elementos JSX. Para los elementos JSX, pasa el nombre del elemento que desea representar. Sin embargo, para los componentes React, debe usar la misma sintaxis como si estuviera representando un componente anidado, por ejemplo, ReactDOM.render(<ComponentToRender />, targetNode) . Utilice esta sintaxis para los componentes de clase ES6 y los componentes funcionales. +
    + +## Instructions +
    +Ambos componentes de Fruits y Vegetables están definidos para usted detrás de escena. Procese ambos componentes como elementos TypesOfFood componente TypesOfFood , a continuación, procese TypesOfFood al DOM. Hay un div con id='challenge-node' disponible para que lo uses. +
    + +## Tests +
    + +```yml +tests: + - text: El componente TypesOfFood debe devolver un único elemento div . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().type() === "div"; })(), "The TypesOfFood component should return a single div element.");' + - text: El componente TypesOfFood debe representar el componente Fruits después del elemento h1 . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(1).name() === "Fruits"; })(), "The TypesOfFood component should render the Fruits component after the h1 element.");' + - text: El componente TypesOfFood debe representar el componente Vegetables después de Fruits . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(TypesOfFood)); return mockedComponent.children().childAt(2).name() === "Vegetables"; })(), "The TypesOfFood component should render the Vegetables component after Fruits.");' + - text: El componente TypesOfFood debe representar en el DOM dentro del div con el id challenge-node . + testString: 'assert((function() { const html = document.getElementById("challenge-node").childNodes[0].innerHTML; return (html === "

    Types of Food:

    Fruits:

    Non-Citrus:

    • Apples
    • Blueberries
    • Strawberries
    • Bananas

    Citrus:

    • Lemon
    • Lime
    • Orange
    • Grapefruit

    Vegetables:

    • Brussel Sprouts
    • Broccoli
    • Squash
    "); })(), "The TypesOfFood component should render to the DOM within the div with the id challenge-node.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +class TypesOfFood extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Types of Food:

    + {/* change code below this line */} + + {/* change code above this line */} +
    + ); + } +}; + +// change code below this line + +``` + +
    + +### Before Test +
    + +```jsx + +const Fruits = () => { + return ( +
    +

    Fruits:

    +

    Non-Citrus:

    +
      +
    • Apples
    • +
    • Blueberries
    • +
    • Strawberries
    • +
    • Bananas
    • +
    +

    Citrus:

    +
      +
    • Lemon
    • +
    • Lime
    • +
    • Orange
    • +
    • Grapefruit
    • +
    +
    + ); +}; +const Vegetables = () => { + return ( +
    +

    Vegetables:

    +
      +
    • Brussel Sprouts
    • +
    • Broccoli
    • +
    • Squash
    • +
    +
    + ); +}; + +``` + +
    + + +
    + +## Solution +
    + + +```js +class TypesOfFood extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    +

    Types of Food:

    + {/* change code below this line */} + + + {/* change code above this line */} +
    + ); + } +}; + +// change code below this line +ReactDOM.render(, document.getElementById('challenge-node')); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-conditionally-from-props.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-conditionally-from-props.spanish.md new file mode 100644 index 0000000000..047573be15 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-conditionally-from-props.spanish.md @@ -0,0 +1,157 @@ +--- +id: 5a24c314108439a4d4036188 +title: Render Conditionally from Props +localeTitle: Procesamiento condicional de apoyos +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hasta ahora, ha visto cómo usar if/else , &&, null y el operador ternario ( condition ? expressionIfTrue : expressionIfFalse ) para tomar decisiones condicionales sobre qué representar y cuándo. Sin embargo, hay un tema importante que queda por discutir que te permite combinar cualquiera o todos estos conceptos con otra poderosa característica React: accesorios. El uso de utilería para generar condicionalmente el código es muy común entre los desarrolladores de React, es decir, utilizan el valor de una prop determinada para tomar decisiones automáticamente sobre qué representar. +En este desafío, configurará un componente secundario para tomar decisiones de representación basadas en accesorios. También usará el operador ternario, pero puede ver cómo varios de los otros conceptos que se cubrieron en los últimos desafíos podrían ser igual de útiles en este contexto. +
    + +## Instructions +
    +El editor de código tiene dos componentes que están parcialmente definidos para usted: un padre llamado GameOfChance y un hijo llamado Results . Se utilizan para crear un juego simple en el que el usuario presiona un botón para ver si gana o pierde. +Primero, necesitará una expresión simple que retorne aleatoriamente un valor diferente cada vez que se ejecute. Puedes usar Math.random() . Este método devuelve un valor entre 0 (incluido) y 1 (exclusivo) cada vez que se llama. Entonces, para probabilidades 50/50, use Math.random() > .5 en su expresión. Estadísticamente hablando, esta expresión devolverá true 50% del tiempo, y false el otro 50%. En la línea 30, reemplace el comentario con esta expresión para completar la declaración de la variable. +Ahora tiene una expresión que puede usar para tomar una decisión aleatoria en el código. A continuación necesitas implementar esto. Procese el componente Results como un elemento secundario de GameOfChance y pase la expression como un prop llamado fiftyFifty . En el componente Results , escriba una expresión ternaria para representar el texto "You win!" o "You lose!" basado en la propuesta fiftyFifty que se transmite desde GameOfChance . Finalmente, asegúrese de que el método handleClick() esté contando correctamente cada turno para que el usuario sepa cuántas veces ha jugado. Esto también sirve para que el usuario sepa que el componente se ha actualizado en caso de que gane o pierda dos veces seguidas. +
    + +## Tests +
    + +```yml +tests: + - text: El componente GameOfChance debe existir y representarse en la página. + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find("GameOfChance").length, 1, "The GameOfChance component should exist and render to the page.");' + - text: GameOfChance debería devolver un único elemento de button . + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find("button").length, 1, "GameOfChance should return a single button element.");' + - text: ' GameOfChance debe devolver una sola instancia del componente Results , que tiene un prop llamado fiftyFifty '. + testString: 'assert(Enzyme.mount(React.createElement(GameOfChance)).find("Results").length === 1 && Enzyme.mount(React.createElement(GameOfChance)).find("Results").props().hasOwnProperty("fiftyFifty") === true, "GameOfChance should return a single instance of the Results component, which has a prop called fiftyFifty.");' + - text: GameOfChance estado de GameOfChance debe inicializar con una propiedad de counter configurada en un valor de 1 . + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).state().counter, 1, "GameOfChance state should be initialized with a property of counter set to a value of 1.");' + - text: 'Cuando el componente GameOfChance se procesa por primera vez en el DOM, se debe devolver un elemento p con el texto interno de Turn: 1 '. + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(GameOfChance)).find("p").text(), "Turn: 1", "When the GameOfChance component is first rendered to the DOM, a p element should be returned with the inner text of Turn: 1.");' + - text: 'Cada vez que se hace clic en el botón, el estado del contador debe incrementarse en un valor de 1, y se debe representar un solo elemento p en el DOM que contiene el texto "Turn: N", donde N es el valor del estado del contador . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find("button").simulate("click"); };const result = () => ({ count: comp.state("counter"), text: comp.find("p").text() });const _1 = () => { simulate(); return waitForIt(() => result())}; const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); assert(_1_val.count === 2 && _1_val.text === "Turn: 2" && _2_val.count === 3 && _2_val.text === "Turn: 3" && _3_val.count === 4 && _3_val.text === "Turn: 4" && _4_val.count === 5 && _4_val.text === "Turn: 5" && _5_val.count === 6 && _5_val.text === "Turn: 6", "Each time the button is clicked, the counter state should be incremented by a value of 1, and a single p element should be rendered to the DOM that contains the text "Turn: N", where N is the value of the counter state."); }; ' + - text: 'Cuando el componente GameOfChance se monta por primera vez en el DOM y cada vez que se hace clic en el botón a continuación, se debe devolver un único elemento h1 que muestre aleatoriamente ¡ You Win! o You Lose! . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(GameOfChance)); const simulate = () => { comp.find("button").simulate("click"); };const result = () => ({ h1: comp.find("h1").length, text: comp.find("h1").text() });const _1 = result(); const _2 = () => { simulate(); return waitForIt(() => result())}; const _3 = () => { simulate(); return waitForIt(() => result())}; const _4 = () => { simulate(); return waitForIt(() => result())}; const _5 = () => { simulate(); return waitForIt(() => result())}; const _6 = () => { simulate(); return waitForIt(() => result())}; const _7 = () => { simulate(); return waitForIt(() => result())}; const _8 = () => { simulate(); return waitForIt(() => result())}; const _9 = () => { simulate(); return waitForIt(() => result())}; const _10 = () => { simulate(); return waitForIt(() => result())}; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const __text = new Set([_1.text, _2_val.text, _3_val.text, _4_val.text, _5_val.text, _6_val.text, _7_val.text, _8_val.text, _9_val.text, _10_val.text]); const __h1 = new Set([_1.h1, _2_val.h1, _3_val.h1, _4_val.h1, _5_val.h1, _6_val.h1, _7_val.h1, _8_val.h1, _9_val.h1, _10_val.h1]); assert(__text.size === 2 && __h1.size === 1, "When the GameOfChance component is first mounted to the DOM and each time the button is clicked thereafter, a single h1 element should be returned that randomly renders either You Win! or You Lose!."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class Results extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +

    + { + /* change code here */ + } +

    + ) + }; +}; + +class GameOfChance extends React.Component { + constructor(props) { + super(props); + this.state = { + counter: 1 + } + this.handleClick = this.handleClick.bind(this); + } + handleClick() { + this.setState({ + counter: 0 // change code here + }); + } + render() { + let expression = null; // change code here + return ( +
    + + { /* change code below this line */ } + + { /* change code above this line */ } +

    {'Turn: ' + this.state.counter}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class Results extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +

    + { + this.props.fiftyFifty ? + 'You Win!' : + 'You Lose!' + } +

    + ) + }; +}; + +class GameOfChance extends React.Component { + constructor(props) { + super(props); + this.state = { + counter: 1 + } + this.handleClick = this.handleClick.bind(this); + } + handleClick() { + this.setState({ + counter: this.state.counter + 1 + }); + } + render() { + const expression = Math.random() > .5; + return ( +
    + + +

    {'Turn: ' + this.state.counter}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-html-elements-to-the-dom.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-html-elements-to-the-dom.spanish.md new file mode 100644 index 0000000000..b0c3c93e42 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-html-elements-to-the-dom.spanish.md @@ -0,0 +1,76 @@ +--- +id: 5a24bbe0dba28a8d3cbd4c5f +title: Render HTML Elements to the DOM +localeTitle: Renderizar elementos HTML al DOM +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hasta ahora, ha aprendido que JSX es una herramienta conveniente para escribir HTML legible dentro de JavaScript. Con React, podemos procesar este JSX directamente al HTML DOM usando la API de renderizado de React conocida como ReactDOM. +ReactDOM ofrece un método simple para representar los elementos React al DOM, que se parece a esto: ReactDOM.render(componentToRender, targetNode) , donde el primer argumento es el elemento o componente React que desea procesar, y el segundo argumento es el DOM nodo al que desea hacer que el componente. +Como era de esperar, se debe llamar a ReactDOM.render() después de las declaraciones del elemento JSX, tal como se deben declarar las variables antes de usarlas. +
    + +## Instructions +
    +El editor de código tiene un componente JSX simple. Utilice el método ReactDOM.render() para procesar este componente en la página. Puede pasar los elementos JSX definidos directamente como primer argumento y usar document.getElementById() para seleccionar el nodo DOM para representarlos. Hay un div con id='challenge-node' disponible para que lo uses. Asegúrate de no cambiar la constante JSX . +
    + +## Tests +
    + +```yml +tests: + - text: La constante JSX debe devolver un elemento div . + testString: 'assert(JSX.type === "div", "The constant JSX should return a div element.");' + - text: El div debe contener una etiqueta h1 como el primer elemento. + testString: 'assert(JSX.props.children[0].type === "h1", "The div should contain an h1 tag as the first element.");' + - text: El div debe contener una etiqueta p como el segundo elemento. + testString: 'assert(JSX.props.children[1].type === "p", "The div should contain a p tag as the second element.");' + - text: El elemento JSX proporcionado se debe representar en el nodo DOM con id challenge-node . + testString: 'assert(document.getElementById("challenge-node").childNodes[0].innerHTML === "

    Hello World

    Lets render this to the DOM

    ", "The provided JSX element should render to the DOM node with id challenge-node.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const JSX = ( +
    +

    Hello World

    +

    Lets render this to the DOM

    +
    +); +// change code below this line + +``` + +
    + + + +
    + +## Solution +
    + + +```js +const JSX = ( +
    +

    Hello World

    +

    Lets render this to the DOM

    +
    +); +// change code below this line +ReactDOM.render(JSX, document.getElementById('challenge-node')); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-react-on-the-server-with-rendertostring.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-react-on-the-server-with-rendertostring.spanish.md new file mode 100644 index 0000000000..01fdd8ab8d --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-react-on-the-server-with-rendertostring.spanish.md @@ -0,0 +1,92 @@ +--- +id: 5a24c314108439a4d403618d +title: Render React on the Server with renderToString +localeTitle: Render React en el servidor con renderToString +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hasta ahora, ha estado renderizando componentes React en el cliente. Normalmente, esto es lo que siempre harás. Sin embargo, hay algunos casos de uso en los que tiene sentido renderizar un componente React en el servidor. Dado que React es una biblioteca de vista de JavaScript y puede ejecutar JavaScript en el servidor con Node, esto es posible. De hecho, React proporciona un método renderToString() que puede utilizar para este propósito. +Hay dos razones clave por las que se puede usar la representación en el servidor en una aplicación del mundo real. Primero, sin hacer esto, sus aplicaciones React consistirán en un archivo HTML relativamente vacío y un gran paquete de JavaScript cuando se cargue inicialmente en el navegador. Es posible que esto no sea ideal para los motores de búsqueda que intentan indexar el contenido de sus páginas para que las personas puedan encontrarlo. Si representa el marcado HTML inicial en el servidor y lo envía al cliente, la carga de la página inicial contiene todo el marcado del que los motores de búsqueda pueden rastrear. En segundo lugar, esto crea una experiencia de carga de página inicial más rápida porque el HTML representado es más pequeño que el código JavaScript de toda la aplicación. React aún podrá reconocer su aplicación y administrarla después de la carga inicial. +
    + +## Instructions +
    +El método renderToString() se proporciona en ReactDOMServer , que está disponible aquí como un objeto global. El método toma un argumento que es un elemento React. Usa esto para renderizar la App a una cadena. +
    + +## Tests +
    + +```yml +tests: + - text: El componente de la App debe representar en una cadena utilizando ReactDOMServer.renderToString . + testString: 'getUserInput => assert(getUserInput("index").replace(/ /g,"").includes("ReactDOMServer.renderToString()") && Enzyme.mount(React.createElement(App)).children().name() === "div", "The App component should render to a string using ReactDOMServer.renderToString.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +class App extends React.Component { + constructor(props) { + super(props); + } + render() { + return
    + } +}; + +// change code below this line + +``` + +
    + +### Before Test +
    + +```jsx +var ReactDOMServer = { renderToString(x) { return null; } }; +``` + +
    + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class App extends React.Component { + constructor(props) { + super(props); + } + render() { + return
    + } +}; + +// change code below this line +ReactDOMServer.renderToString(); +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface-another-way.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface-another-way.spanish.md new file mode 100644 index 0000000000..0c4e8b1a16 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface-another-way.spanish.md @@ -0,0 +1,107 @@ +--- +id: 5a24c314108439a4d4036172 +title: Render State in the User Interface Another Way +localeTitle: Estado de render en la interfaz de usuario de otra manera +challengeType: 6 +isRequired: false +--- + +## Description +
    +Hay otra forma de acceder al state en un componente. En el método render() , antes de la declaración de return , puede escribir JavaScript directamente. Por ejemplo, podría declarar funciones, acceder a datos de state o props , realizar cálculos en estos datos, etc. Luego, puede asignar cualquier dato a las variables, a las que tiene acceso en la declaración de return . +
    + +## Instructions +
    +En el método de procesamiento de MyComponent , defina una const llamada name y establezca que sea igual al valor del nombre en el state del componente. Debido a que puede escribir JavaScript directamente en esta parte del código, no tiene que incluir esta referencia entre llaves. +A continuación, en la declaración de retorno, renderice este valor en una etiqueta h1 usando el name la variable. Recuerde, debe usar la sintaxis JSX (llaves para JavaScript) en la declaración de devolución. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debe tener un name clave con el valor freeCodeCamp almacenado en su estado. + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "freeCodeCamp", "MyComponent should have a key name with value freeCodeCamp stored in its state.");' + - text: MyComponent debe representar un encabezado h1 incluido en un solo div . + testString: 'assert(/

    .*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), "MyComponent should render an h1 header enclosed in a single div.");' + - text: 'La etiqueta h1 representada debe incluir una referencia a {name} .' + testString: 'getUserInput => assert(/

    \n*\s*\{\s*name\s*\}\s*\n*<\/h1>/.test(getUserInput("index")), "The rendered h1 tag should include a reference to {name}.");' + - text: El encabezado h1 representado debe contener texto representado desde el estado del componente. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "TestName" }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === "

    TestName

    ", "The rendered h1 header should contain text rendered from the component's state."); };' + +``` + +

    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'freeCodeCamp' + } + } + render() { + // change code below this line + + // change code above this line + return ( +
    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'freeCodeCamp' + } + } + render() { + // change code below this line + const name = this.state.name; + // change code above this line + return ( +
    + { /* change code below this line */ } +

    {name}

    + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface.spanish.md new file mode 100644 index 0000000000..f66253dd62 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-state-in-the-user-interface.spanish.md @@ -0,0 +1,102 @@ +--- +id: 5a24c314108439a4d4036171 +title: Render State in the User Interface +localeTitle: Estado de render en la interfaz de usuario +challengeType: 6 +isRequired: false +--- + +## Description +
    +Una vez que define el estado inicial de un componente, puede mostrar cualquier parte de él en la interfaz de usuario que se representa. Si un componente tiene estado, siempre tendrá acceso a los datos en state en su método render() . Puede acceder a los datos con this.state . +Si desea acceder a un valor de estado dentro del return del método de procesamiento, debe incluir el valor entre llaves. +State es una de las características más poderosas de los componentes en React. Le permite hacer un seguimiento de los datos importantes en su aplicación y generar una IU en respuesta a los cambios en estos datos. Si sus datos cambian, su interfaz de usuario cambiará. React utiliza lo que se llama un DOM virtual, para realizar un seguimiento de los cambios detrás de la escena. Cuando se actualizan los datos del estado, se activa una nueva representación de los componentes que utilizan esos datos, incluidos los componentes secundarios que recibieron los datos como prop. Reacciona actualiza el DOM real, pero solo cuando es necesario. Esto significa que no tiene que preocuparse por cambiar el DOM. Simplemente declara cómo debería ser la interfaz de usuario. +Tenga en cuenta que si hace que un componente sea con estado, ningún otro componente es consciente de su state . Su state es completamente encapsulado, o local a ese componente, a menos que pase datos de estado a un componente secundario como props . Esta noción de state encapsulado es muy importante porque le permite escribir cierta lógica, y luego tener esa lógica contenida y aislada en un lugar en su código. +
    + +## Instructions +
    +En el editor de código, MyComponent ya tiene estado. Defina una etiqueta h1 en el método de procesamiento del componente que representa el valor de name del estado del componente. +Nota: El h1 solo debe representar el valor del state y nada más. En JSX, cualquier código que escriba con llaves { } será tratado como JavaScript. Entonces, para acceder al valor desde el state simplemente incluya la referencia entre llaves. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debe tener un name clave con el valor freeCodeCamp almacenado en su estado. + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "freeCodeCamp", "MyComponent should have a key name with value freeCodeCamp stored in its state.");' + - text: MyComponent debe representar un encabezado h1 incluido en un solo div . + testString: 'assert(/

    .*<\/h1><\/div>/.test(Enzyme.mount(React.createElement(MyComponent)).html()), "MyComponent should render an h1 header enclosed in a single div.");' + - text: El encabezado h1 representado debe contener texto representado desde el estado del componente. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "TestName" }); return waitForIt(() => mockedComponent.html()) }; const firstValue = await first(); assert(firstValue === "

    TestName

    ", "The rendered h1 header should contain text rendered from the component's state.");};' + +``` + +

    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'freeCodeCamp' + } + } + render() { + return ( +
    + { /* change code below this line */ } + + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'freeCodeCamp' + } + } + render() { + return ( +
    + { /* change code below this line */ } +

    {this.state.name}

    + { /* change code above this line */ } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/render-with-an-if-else-condition.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/render-with-an-if-else-condition.spanish.md new file mode 100644 index 0000000000..e2e4833a27 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/render-with-an-if-else-condition.spanish.md @@ -0,0 +1,122 @@ +--- +id: 5a24c314108439a4d4036184 +title: Render with an If-Else Condition +localeTitle: Render con una condición de si-else +challengeType: 6 +isRequired: false +--- + +## Description +
    +Otra aplicación del uso de JavaScript para controlar su vista renderizada es vincular los elementos que se representan a una condición. Cuando la condición es verdadera, una vista se renderiza. Cuando es falso, es una vista diferente. Puede hacer esto con una instrucción if/else estándar en el método render() de un componente React. +
    + +## Instructions +
    +MyComponent contiene un boolean en su estado que rastrea si desea mostrar algún elemento en la interfaz de usuario o no. El button cambia el estado de este valor. Actualmente, rinde la misma interfaz de usuario cada vez. Reescriba el método render() con una instrucción if/else para que si la display es true , devuelva el marcado actual. De lo contrario, devuelva el marcado sin el elemento h1 . +Nota: Debe escribir un if/else para pasar las pruebas. El uso del operador ternario no pasará aquí. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debería existir y renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("MyComponent").length === 1; })(), "MyComponent should exist and render.");' + - text: 'Cuando la display está configurada como true , deberían display un div , un button y h1 .' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find("div").length === 1 && mockedComponent.find("div").children().length === 2 && mockedComponent.find("button").length === 1 && mockedComponent.find("h1").length === 1, "When display is set to true, a div, button, and h1 should render."); }; ' + - text: 'Cuando la display está configurada en false , solo deberían display un button div y'. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(mockedComponent.find("div").length === 1 && mockedComponent.find("div").children().length === 1 && mockedComponent.find("button").length === 1 && mockedComponent.find("h1").length === 0, "When display is set to false, only a div and button should render."); }; ' + - text: El método de render debería usar una instrucción if/else para verificar la condición de this.state.display . + testString: 'getUserInput => assert(getUserInput("index").includes("if") && getUserInput("index").includes("else"), "The render method should use an if/else statement to check the condition of this.state.display.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + display: true + } + this.toggleDisplay = this.toggleDisplay.bind(this); + } + toggleDisplay() { + this.setState({ + display: !this.state.display + }); + } + render() { + // change code below this line + + return ( +
    + +

    Displayed!

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + display: true + } + this.toggleDisplay = this.toggleDisplay.bind(this); + } + toggleDisplay() { + this.setState({ + display: !this.state.display + }); + } + render() { + // change code below this line + if (this.state.display) { + return ( +
    + +

    Displayed!

    +
    + ); + } else { + return ( +
    + +
    + ); + } + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/review-using-props-with-stateless-functional-components.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/review-using-props-with-stateless-functional-components.spanish.md new file mode 100644 index 0000000000..da4c4d5eac --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/review-using-props-with-stateless-functional-components.spanish.md @@ -0,0 +1,124 @@ +--- +id: 5a24c314108439a4d403616f +title: Review Using Props with Stateless Functional Components +localeTitle: Revisión usando accesorios con componentes funcionales sin estado +challengeType: 6 +isRequired: false +--- + +## Description +
    +A excepción del último desafío, ha estado pasando apoyos a componentes funcionales sin estado. Estos componentes actúan como funciones puras. Aceptan props como entrada y devuelven la misma vista cada vez que se pasan los mismos props. Puede que se pregunte qué es el estado, y el próximo desafío lo cubrirá con más detalle. Antes de eso, aquí hay una revisión de la terminología de los componentes. +Un componente funcional sin estado es cualquier función que se escribe que acepta props y devuelve JSX. Un componente sin estado , por otro lado, es una clase que extiende React.Component , pero no usa el estado interno (cubierto en el próximo desafío). Finalmente, un componente con estado es cualquier componente que mantiene su propio estado interno. Es posible que vea los componentes con estado referidos simplemente como componentes o componentes React. +Un patrón común es tratar de minimizar la falta de estado y crear componentes funcionales sin estado siempre que sea posible. Esto ayuda a incluir la administración de su estado en un área específica de su aplicación. A su vez, esto mejora el desarrollo y el mantenimiento de su aplicación al hacer que sea más fácil seguir cómo los cambios de estado afectan su comportamiento. +
    + +## Instructions +
    +El editor de código tiene un componente CampSite que procesa un componente Camper como un elemento secundario. Defina el componente Camper y asígnele accesorios predeterminados de { name: 'CamperBot' } . Dentro del componente Camper , genere el código que desee, pero asegúrese de tener un elemento p que incluya solo el valor del name que se pasa como prop . Finalmente, defina propTypes en el componente Camper para requerir que se proporcione un name como prop y verifique que sea de tipo string . +
    + +## Tests +
    + +```yml +tests: + - text: El componente CampSite debe renderizar. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find("CampSite").length === 1; })(), "The CampSite component should render.");' + - text: El componente Camper debe hacer. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find("Camper").length === 1; })(), "The Camper component should render.");' + - text: El componente Camper debe incluir accesorios predeterminados que asignan la cadena CamperBot al name la clave. + testString: 'getUserInput => assert((function() { const noWhiteSpace = getUserInput("index").replace(/\s/g, ""); const verify1 = "Camper.defaultProps={name:\"CamperBot\"}"; const verify2 = "Camper.defaultProps={name:"CamperBot"}"; return (noWhiteSpace.includes(verify1) || noWhiteSpace.includes(verify2)); })(), "The Camper component should include default props which assign the string CamperBot to the key name.");' + - text: El componente Camper debe incluir tipos de prop que requieren que el name prop sea de tipo string . + testString: 'getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); const noWhiteSpace = getUserInput("index").replace(/\s/g, ""); const verifyDefaultProps = "Camper.propTypes={name:PropTypes.string.isRequired}"; return noWhiteSpace.includes(verifyDefaultProps); })(), "The Camper component should include prop types which require the name prop to be of type string.");' + - text: El componente Camper debe contener un elemento p con solo el texto del name prop. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(CampSite)); return mockedComponent.find("p").text() === mockedComponent.find("Camper").props().name; })(), "The Camper component should contain a p element with only the text from the name prop.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class CampSite extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    + +
    + ); + } +}; +// change code below this line + +``` + +
    + +### Before Test +
    + +```jsx +var PropTypes = { + string: { isRequired: true } +}; +``` + +
    + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class CampSite extends React.Component { + constructor(props) { + super(props); + } + render() { + return ( +
    + +
    + ); + } +}; +// change code below this line + +const Camper = (props) => { + return ( +
    +

    {props.name}

    +
    + ); +}; + +Camper.propTypes = { + name: PropTypes.string.isRequired +}; + +Camper.defaultProps = { + name: 'CamperBot' +}; + +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/set-state-with-this.setstate.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/set-state-with-this.setstate.spanish.md new file mode 100644 index 0000000000..af08ec5f30 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/set-state-with-this.setstate.spanish.md @@ -0,0 +1,115 @@ +--- +id: 5a24c314108439a4d4036173 +title: Set State with this.setState +localeTitle: Establecer estado con this.setState +challengeType: 6 +isRequired: false +--- + +## Description +
    +Los desafíos anteriores cubrieron el state componente y cómo inicializar el estado en el constructor . También hay una manera de cambiar el state del componente. React proporciona un método para actualizar el state componente llamado setState . Llama al método setState dentro de su clase de componente así: this.setState() , pasando un objeto con pares clave-valor. Las claves son las propiedades de su estado y los valores son los datos de estado actualizados. Por ejemplo, si almacenáramos un username de username en estado y quisiéramos actualizarlo, se vería así: +
    this.setState({
      username: 'Lewis'
    });
    +React espera que nunca modifique el state directamente, en su lugar, siempre use this.setState() cuando ocurran cambios de estado. Además, debe tener en cuenta que React puede generar varias actualizaciones de estado por lotes para mejorar el rendimiento. Lo que esto significa es que las actualizaciones de estado a través del método setState pueden ser asíncronas. Hay una sintaxis alternativa para el método setState que proporciona una forma de solucionar este problema. Esto rara vez es necesario, pero es bueno tenerlo en cuenta. Por favor, consulte la documentación de React para más detalles. +
    + +## Instructions +
    +Hay un elemento de button en el editor de código que tiene un controlador onClick() . Este controlador se activa cuando el button recibe un evento de clic en el navegador y ejecuta el método handleClick definido en MyComponent . Dentro del método handleClick , actualice el state del componente usando this.setState() . Establezca la propiedad de name en state para que sea igual a la cadena React Rocks! . +Haga clic en el botón y observe la actualización del estado renderizado. No se preocupe si no entiende completamente cómo funciona el código del controlador de clics en este momento. Está cubierto en los próximos desafíos. +
    + +## Tests +
    + +```yml +tests: + - text: 'El estado de MyComponent debe MyComponent con el par de valores clave { name: Initial State } .' + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).state("name") === "Initial State", "The state of MyComponent should initialize with the key value pair { name: Initial State }.");' + - text: MyComponent debe hacer un encabezado h1 . + testString: 'assert(Enzyme.mount(React.createElement(MyComponent)).find("h1").length === 1, "MyComponent should render an h1 header.");' + - text: El encabezado h1 representado debe contener texto representado desde el estado del componente. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "TestName" }); return waitForIt(() => mockedComponent.html()); }; const firstValue = await first(); assert(/

    TestName<\/h1>/.test(firstValue), "The rendered h1 header should contain text rendered from the component's state."); };' + - text: ¡Llamar al método handleClick en MyComponent debe establecer la propiedad de nombre en el estado para igualar React Rocks! . + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const first = () => { mockedComponent.setState({ name: "Before" }); return waitForIt(() => mockedComponent.state("name")); }; const second = () => { mockedComponent.instance().handleClick(); return waitForIt(() => mockedComponent.state("name")); }; const firstValue = await first(); const secondValue = await second(); assert(firstValue === "Before" && secondValue === "React Rocks!", "Calling the handleClick method on MyComponent should set the name property in state to equal React Rocks!."); };' + +``` + +

    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'Initial State' + }; + this.handleClick = this.handleClick.bind(this); + } + handleClick() { + // change code below this line + + // change code above this line + } + render() { + return ( +
    + +

    {this.state.name}

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + name: 'Initial State' + }; + this.handleClick = this.handleClick.bind(this); + } + handleClick() { + // change code below this line + this.setState({ + name: 'React Rocks!' + }); + // change code above this line + } + render() { + return ( +
    + +

    {this.state.name}

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/use--for-a-more-concise-conditional.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/use--for-a-more-concise-conditional.spanish.md new file mode 100644 index 0000000000..1ef0d0e7b9 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/use--for-a-more-concise-conditional.spanish.md @@ -0,0 +1,114 @@ +--- +id: 5a24c314108439a4d4036185 +title: Use && for a More Concise Conditional +localeTitle: Use && para un condicional más conciso +challengeType: 6 +isRequired: false +--- + +## Description +
    +Las declaraciones if / else funcionaron en el último desafío, pero hay una forma más concisa de lograr el mismo resultado. Imagine que está rastreando varias condiciones en un componente y desea que se representen diferentes elementos en función de cada una de estas condiciones. Si escribe muchas else if instrucciones, else if declaraciones devuelven interfaces de usuario ligeramente diferentes, puede repetir el código que deja espacio para el error. En su lugar, puede utilizar el operador lógico && para realizar la lógica condicional de una manera más concisa. Esto es posible porque desea verificar si una condición es true y, si lo es, devolver algún margen de beneficio. Aquí hay un ejemplo: +{condition && <p>markup</p>} +Si la condition es true , se devolverá la marca. Si la condición es false , la operación devolverá inmediatamente false después de evaluar la condition y no devolverá nada. Puede incluir estas declaraciones directamente en su JSX y encadenar varias condiciones juntas escribiendo && después de cada una. Esto le permite manejar una lógica condicional más compleja en su método render() sin repetir mucho código. +
    + +## Instructions +
    +Resuelva el ejemplo anterior nuevamente, de modo que h1 solo display si la display es true , pero use el operador lógico && lugar de una instrucción if/else . +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debería existir y renderizarse. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("MyComponent").length; })(), "MyComponent should exist and render.");' + - text: 'Cuando la display está configurada como true , deberían display un div , un button y h1 .' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 2 && updated.find("button").length === 1 && updated.find("h1").length === 1, "When display is set to true, a div, button, and h1 should render."); }; ' + - text: 'Cuando la display está configurada en false , solo deberían display un button div y'. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 1 && updated.find("button").length === 1 && updated.find("h1").length === 0, "When display is set to false, only a div and button should render."); }; ' + - text: El método de representación debe utilizar el operador lógico && para verificar la condición de this.state.display. + testString: 'getUserInput => assert(getUserInput("index").includes("&&"), "The render method should use the && logical operator to check the condition of this.state.display.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + display: true + } + this.toggleDisplay = this.toggleDisplay.bind(this); + } + toggleDisplay() { + this.setState({ + display: !this.state.display + }); + } + render() { + // change code below this line + return ( +
    + +

    Displayed!

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + display: true + } + this.toggleDisplay = this.toggleDisplay.bind(this); + } + toggleDisplay() { + this.setState({ + display: !this.state.display + }); + } + render() { + // change code below this line + return ( +
    + + {this.state.display &&

    Displayed!

    } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering.spanish.md new file mode 100644 index 0000000000..7a7e834fd7 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering.spanish.md @@ -0,0 +1,168 @@ +--- +id: 5a24c314108439a4d4036187 +title: Use a Ternary Expression for Conditional Rendering +localeTitle: Utilice una expresión ternaria para la representación condicional +challengeType: 6 +isRequired: false +--- + +## Description +
    +Antes de pasar a las técnicas de representación dinámica, hay una última forma de usar condicionales de JavaScript incorporados para representar lo que desea: el operador ternario . El operador ternario se utiliza a menudo como acceso directo para las declaraciones if/else en JavaScript. No son tan robustos como las declaraciones tradicionales if/else , pero son muy populares entre los desarrolladores de React. Una razón para esto se debe a cómo se compila JSX, if/else sentencias no se pueden insertar directamente en el código JSX. Es posible que haya notado esto hace un par de desafíos: cuando se requería una declaración if/else , siempre estaba fuera de la declaración de return . Las expresiones ternarias pueden ser una excelente alternativa si desea implementar lógica condicional dentro de su JSX. Recuerde que un operador ternario tiene tres partes, pero puede combinar varias expresiones ternarias juntas. Aquí está la sintaxis básica: +
    condition ? expressionIfTrue : expressionIfFalse
    +
    + +## Instructions +
    +El editor de código tiene tres constantes definidas dentro del CheckUserAge render() del componente CheckUserAge . Se denominan buttonOne , buttonTwo y buttonThree . A cada uno de estos se les asigna una expresión JSX simple que representa un elemento de botón. Primero, inicialice el estado de CheckUserAge con input y userAge ambos configurados en valores de una cadena vacía. +Una vez que el componente está brindando información a la página, los usuarios deben tener una forma de interactuar con él. Dentro de la declaración de return del componente, configure una expresión ternaria que implemente la siguiente lógica: cuando la página se carga por primera vez, renderice el botón de envío, buttonOne , a la página. Luego, cuando un usuario ingresa su edad y hace clic en el botón, renderiza un botón diferente según la edad. Si un usuario ingresa un número menor que 18 , render buttonThree . Si un usuario ingresa un número mayor o igual a 18 , renderice el buttonTwo . +
    + +## Tests +
    + +```yml +tests: + - text: El componente CheckUserAge debe procesarse con un solo elemento de input y un solo elemento de button . + testString: 'assert(Enzyme.mount(React.createElement(CheckUserAge)).find("div").find("input").length === 1 && Enzyme.mount(React.createElement(CheckUserAge)).find("div").find("button").length === 1, "The CheckUserAge component should render with a single input element and a single button element.");' + - text: 'El CheckUserAge componente CheckUserAge debe inicializarse con una propiedad de userAge y una propiedad de input , ambas configuradas con el valor de una cadena vacía'. + testString: 'assert(Enzyme.mount(React.createElement(CheckUserAge)).state().input === "" && Enzyme.mount(React.createElement(CheckUserAge)).state().userAge === "", "The CheckUserAge component's state should be initialized with a property of userAge and a property of input, both set to a value of an empty string.");' + - text: 'Cuando el componente CheckUserAge se procesa por primera vez en el DOM, el texto interno del button debe ser Enviar.' + testString: 'assert(Enzyme.mount(React.createElement(CheckUserAge)).find("button").text() === "Submit", "When the CheckUserAge component is first rendered to the DOM, the button's inner text should be Submit.");' + - text: 'Cuando se introduce un número inferior a 18 a la input elemento y el button se hace clic en el button 's texto interno debe leer You Shall Not Pass .' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find("button").text(); const enter3AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "3" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const enter17AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "17" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const userAge3 = await enter3AndClickButton(); const userAge17 = await enter17AndClickButton(); assert(initialButton === "Submit" && userAge3 === "You Shall Not Pass" && userAge17 === "You Shall Not Pass", "When a number of less than 18 is entered into the input element and the button is clicked, the button's inner text should read You Shall Not Pass."); }; ' + - text: 'Cuando se introduce un número mayor o igual a 18 a la input elemento y el button se hace clic en el button 's texto interno debe leer You May Enter .' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const initialButton = mockedComponent.find("button").text(); const enter18AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "18" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const enter35AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "35" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const userAge18 = await enter18AndClickButton(); const userAge35 = await enter35AndClickButton(); assert(initialButton === "Submit" && userAge18 === "You May Enter" && userAge35 === "You May Enter", "When a number greater than or equal to 18 is entered into the input element and the button is clicked, the button's inner text should read You May Enter."); }; ' + - text: "Una vez que se ha enviado un número y el valor de la input se cambia de nuevo, el button debería volver a leer Submit ". + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(CheckUserAge)); const enter18AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "18" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const changeInputDontClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "5" }}); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const enter10AndClickButton = () => { mockedComponent.find("input").simulate("change", {target: { value: "10" }}); mockedComponent.find("button").simulate("click"); return waitForIt(() => { mockedComponent.update(); return mockedComponent.find("button").text(); }); }; const userAge18 = await enter18AndClickButton(); const changeInput1 = await changeInputDontClickButton(); const userAge10 = await enter10AndClickButton(); const changeInput2 = await changeInputDontClickButton(); assert(userAge18 === "You May Enter" && changeInput1 === "Submit" && userAge10 === "You Shall Not Pass" && changeInput2 === "Submit", "Once a number has been submitted, and the value of the input is once again changed, the button should return to reading Submit."); }; ' + - text: Su código no debe contener ninguna declaración if/else . + testString: 'assert(new RegExp(/(\s|;)if(\s|\()/).test(Enzyme.mount(React.createElement(CheckUserAge)).instance().render.toString()) === false, "Your code should not contain any if/else statements.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx + +const inputStyle = { + width: 235, + margin: 5 +} + +class CheckUserAge extends React.Component { + constructor(props) { + super(props); + // change code below this line + + // change code above this line + this.submit = this.submit.bind(this); + this.handleChange = this.handleChange.bind(this); + } + handleChange(e) { + this.setState({ + input: e.target.value, + userAge: " + }); + } + submit() { + this.setState({ + userAge: this.state.input + }); + } + render() { + const buttonOne = ; + const buttonTwo = ; + const buttonThree = ; + return ( +
    +

    Enter Your Age to Continue

    +
    + { + /* change code here */ + } +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const inputStyle = { + width: 235, + margin: 5 +} + +class CheckUserAge extends React.Component { + constructor(props) { + super(props); + this.state = { + userAge: ", + input: " + } + this.submit = this.submit.bind(this); + this.handleChange = this.handleChange.bind(this); + } + handleChange(e) { + this.setState({ + input: e.target.value, + userAge: " + }); + } + submit() { + this.setState({ + userAge: this.state.input + }); + } + render() { + const buttonOne = ; + const buttonTwo = ; + const buttonThree = ; + return ( +
    +

    Enter Your Age to Continue

    +
    + { + this.state.userAge === " ? + buttonOne : + this.state.userAge >= 18 ? + buttonTwo : + buttonThree + } +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/use-advanced-javascript-in-react-render-method.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/use-advanced-javascript-in-react-render-method.spanish.md new file mode 100644 index 0000000000..6e7d78ed74 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/use-advanced-javascript-in-react-render-method.spanish.md @@ -0,0 +1,197 @@ +--- +id: 5a24c314108439a4d4036183 +title: Use Advanced JavaScript in React Render Method +localeTitle: Utilice JavaScript avanzado en el método React Render +challengeType: 6 +isRequired: false +--- + +## Description +
    +En los desafíos anteriores, aprendió cómo inyectar código JavaScript en el código JSX usando llaves, { } , para tareas como acceder a accesorios, aprobar accesorios, acceder a estados, insertar comentarios en su código y, más recientemente, diseñar estilos para sus componentes. Estos son todos los casos de uso comunes para poner JavaScript en JSX, pero no son la única forma en que puede utilizar el código JavaScript en sus componentes React. +También puede escribir JavaScript directamente en sus métodos de render , antes de la declaración de return , sin insertarlo dentro de llaves. Esto se debe a que aún no está dentro del código JSX. Cuando desee utilizar una variable más adelante en el código JSX dentro de la declaración de return , coloque el nombre de la variable entre llaves. +
    + +## Instructions +
    +En el código provisto, el método de render tiene una matriz que contiene 20 frases para representar las respuestas encontradas en el clásico juguete de la bola mágica de los ochenta. El evento de clic de botón está ligado al ask método, por lo que cada vez que se hace clic en el botón de un número aleatorio se genera y se almacena como el randomIndex en el estado. En la línea 52, borra la cadena "change me!" y reasigne la answer constante para que su código acceda al azar a un índice diferente de la possibleAnswers matriz de answer cada vez que se actualice el componente. Finalmente, inserta la answer const dentro de las etiquetas p . +
    + +## Tests +
    + +```yml +tests: + - text: El componente MagicEightBall debe existir y debe MagicEightBall en la página. + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).find("MagicEightBall").length, 1, "The MagicEightBall component should exist and should render to the page.");' + - text: El primer hijo de MagicEightBall debería ser un elemento de input . + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(0).name(), "input", "MagicEightBall's first child should be an input element.");' + - text: El tercer hijo de MagicEightBall debería ser un elemento de button . + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MagicEightBall)).children().childAt(2).name(), "button", "MagicEightBall's third child should be a button element.");' + - text: El estado de MagicEightBall debe inicializarse con una propiedad de userInput y una propiedad de randomIndex ambas configuradas en un valor de una cadena vacía. + testString: 'assert(Enzyme.mount(React.createElement(MagicEightBall)).state("randomIndex") === "" && Enzyme.mount(React.createElement(MagicEightBall)).state("userInput") === "", "MagicEightBall's state should be initialized with a property of userInput and a property of randomIndex both set to a value of an empty string.");' + - text: "Cuando MagicEightBall se monta por primera vez en el DOM, debe devolver un elemento p vacío". + testString: 'assert(Enzyme.mount(React.createElement(MagicEightBall)).find("p").length === 1 && Enzyme.mount(React.createElement(MagicEightBall)).find("p").text() === "", "When MagicEightBall is first mounted to the DOM, it should return an empty p element.");' + - text: "Cuando se ingresa texto en el elemento de input y se hace clic en el botón, el componente MagicEightBall debería devolver un elemento p que contenga un elemento aleatorio de la possibleAnswers matriz de MagicEightBall ". + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MagicEightBall)); const simulate = () => { comp.find("input").simulate("change", { target: { value: "test?" }}); comp.find("button").simulate("click"); }; const result = () => comp.find("p").text(); const _1 = () => { simulate(); return waitForIt(() => result()) }; const _2 = () => { simulate(); return waitForIt(() => result()) }; const _3 = () => { simulate(); return waitForIt(() => result()) }; const _4 = () => { simulate(); return waitForIt(() => result()) }; const _5 = () => { simulate(); return waitForIt(() => result()) }; const _6 = () => { simulate(); return waitForIt(() => result()) }; const _7 = () => { simulate(); return waitForIt(() => result()) }; const _8 = () => { simulate(); return waitForIt(() => result()) }; const _9 = () => { simulate(); return waitForIt(() => result()) }; const _10 = () => { simulate(); return waitForIt(() => result()) }; const _1_val = await _1(); const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); const _5_val = await _5(); const _6_val = await _6(); const _7_val = await _7(); const _8_val = await _8(); const _9_val = await _9(); const _10_val = await _10(); const actualAnswers = [_1_val, _2_val, _3_val, _4_val, _5_val, _6_val, _7_val, _8_val, _9_val, _10_val]; const hasIndex = actualAnswers.filter((answer, i) => possibleAnswers.indexOf(answer) !== -1); const notAllEqual = new Set(actualAnswers); assert(notAllEqual.size > 1 && hasIndex.length === 10, "When text is entered into the input element and the button is clicked, the MagicEightBall component should return a p element that contains a random element from the possibleAnswers array.");}' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const inputStyle = { + width: 235, + margin: 5 +} + +class MagicEightBall extends React.Component { + constructor(props) { + super(props); + this.state = { + userInput: ", + randomIndex: " + } + this.ask = this.ask.bind(this); + this.handleChange = this.handleChange.bind(this); + } + ask() { + if (this.state.userInput) { + this.setState({ + randomIndex: Math.floor(Math.random() * 20), + userInput: " + }); + } + } + handleChange(event) { + this.setState({ + userInput: event.target.value + }); + } + render() { + const possibleAnswers = [ + 'It is certain', + 'It is decidedly so', + 'Without a doubt', + 'Yes, definitely', + 'You may rely on it', + 'As I see it, yes', + 'Outlook good', + 'Yes', + 'Signs point to yes', + 'Reply hazy try again', + 'Ask again later', + 'Better not tell you now', + 'Cannot predict now', + 'Concentrate and ask again', + 'Don\'t count on it', + 'My reply is no', + 'My sources say no', + 'Most likely', + 'Outlook not so good', + 'Very doubtful' + ]; + const answer = 'change me!' // << change code here + return ( +
    +
    +
    +

    Answer:

    +

    + { /* change code below this line */ } + + { /* change code above this line */ } +

    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +const inputStyle = { + width: 235, + margin: 5 +} + +class MagicEightBall extends React.Component { + constructor(props) { + super(props); + this.state = { + userInput: ", + randomIndex: " + } + this.ask = this.ask.bind(this); + this.handleChange = this.handleChange.bind(this); + } + ask() { + if (this.state.userInput) { + this.setState({ + randomIndex: Math.floor(Math.random() * 20), + userInput: " + }); + } + } + handleChange(event) { + this.setState({ + userInput: event.target.value + }); + } + render() { + const possibleAnswers = [ + "It is certain", "It is decidedly so", "Without a doubt", + "Yes, definitely", "You may rely on it", "As I see it, yes", + "Outlook good", "Yes", "Signs point to yes", "Reply hazy try again", + "Ask again later", "Better not tell you now", "Cannot predict now", + "Concentrate and ask again", "Don't count on it", "My reply is no", + "My sources say no", "Outlook not so good","Very doubtful", "Most likely" + ]; + const answer = possibleAnswers[this.state.randomIndex]; + return ( +
    +
    +
    +

    Answer:

    +

    + {answer} +

    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.filter-to-dynamically-filter-an-array.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.filter-to-dynamically-filter-an-array.spanish.md new file mode 100644 index 0000000000..6d2112de9b --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.filter-to-dynamically-filter-an-array.spanish.md @@ -0,0 +1,165 @@ +--- +id: 5a24c314108439a4d403618c +title: Use Array.filter() to Dynamically Filter an Array +localeTitle: Utilice Array.filter () para filtrar dinámicamente una matriz +challengeType: 6 +isRequired: false +--- + +## Description +
    +El método de matriz de map es una herramienta poderosa que usará a menudo cuando trabaje con React. Otro método relacionado con el map es el filter , que filtra el contenido de una matriz según una condición y luego devuelve una nueva matriz. Por ejemplo, si tiene una serie de usuarios que tienen una propiedad en online que puede configurarse como true o false , puede filtrar solo aquellos usuarios que están en línea escribiendo: +let onlineUsers = users.filter(user => user.online); que los usuarios en línea let onlineUsers = users.filter(user => user.online); +
    + +## Instructions +
    +En el editor de código, el state MyComponent se inicializa con una matriz de usuarios. Algunos usuarios están en línea y otros no. Filtre la matriz para ver solo los usuarios que están en línea. Para hacer esto, primero use el filter para devolver una nueva matriz que contenga solo los usuarios cuya propiedad en online es true . Luego, en la variable renderOnline , renderOnline sobre la matriz filtrada y devuelva un elemento li para cada usuario que contenga el texto de su username de username . Asegúrese de incluir también una key única, como en los últimos desafíos. +
    + +## Tests +
    + +```yml +tests: + - text: MyComponent debería existir y renderizarse a la página. + testString: 'assert.strictEqual(Enzyme.mount(React.createElement(MyComponent)).find("MyComponent").length, 1, "MyComponent should exist and render to the page.");' + - text: El estado de MyComponent debería inicializarse a una matriz de seis usuarios ". + testString: 'assert(Array.isArray(Enzyme.mount(React.createElement(MyComponent)).state("users")) === true && Enzyme.mount(React.createElement(MyComponent)).state("users").length === 6, "MyComponent's state should be initialized to an array of six users.");' + - text: ' MyComponent debe devolver un div , un h1 , y luego una lista desordenada que contiene elementos li para cada usuario cuyo estado en línea se establece en true .' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: "Jeff", online: bool }, { username: "Alan", online: bool }, { username: "Mary", online: bool }, { username: "Jim", online: bool }, { username: "Laura", online: bool } ]}); const result = () => comp.find("li").length; const _1 = result(); const _2 = () => { comp.setState(users(true)); return waitForIt(() => result()) }; const _3 = () => { comp.setState(users(false)); return waitForIt(() => result()) }; const _4 = () => { comp.setState({ users: [] }); return waitForIt(() => result()) }; const _2_val = await _2(); const _3_val = await _3(); const _4_val = await _4(); assert(comp.find("div").length === 1 && comp.find("h1").length === 1 && comp.find("ul").length === 1 && _1 === 4 && _2_val === 5 && _3_val === 0 && _4_val === 0, "MyComponent should return a div, an h1, and then an unordered list containing li elements for every user whose online status is set to true."); }; ' + - text: MyComponent debe representar elementos li que contengan el nombre de usuario de cada usuario en línea. + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const comp = Enzyme.mount(React.createElement(MyComponent)); const users = (bool) => ({users:[ { username: "Jeff", online: bool }, { username: "Alan", online: bool }, { username: "Mary", online: bool }, { username: "Jim", online: bool }, { username: "Laura", online: bool } ]}); const ul = () => { comp.setState(users(true)); return waitForIt(() => comp.find("ul").html()) }; const html = await ul(); assert(html === "
    • Jeff
    • Alan
    • Mary
    • Jim
    • Laura
    ", "MyComponent should render li elements that contain the username of each online user."); }; ' + - text: Cada elemento del elemento de la lista debe tener un atributo de key único. + testString: 'assert((() => { const ul = Enzyme.mount(React.createElement(MyComponent)).find("ul"); console.log(ul.debug()); const keys = new Set([ ul.childAt(0).key(), ul.childAt(1).key(), ul.childAt(2).key(), ul.childAt(3).key() ]); return keys.size === 4; })(), "Each list item element should have a unique key attribute.");' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + users: [ + { + username: 'Jeff', + online: true + }, + { + username: 'Alan', + online: false + }, + { + username: 'Mary', + online: true + }, + { + username: 'Jim', + online: false + }, + { + username: 'Sara', + online: true + }, + { + username: 'Laura', + online: true + } + ] + } + } + render() { + const usersOnline = null; // change code here + const renderOnline = null; // change code here + return ( +
    +

    Current Online Users:

    +
      + {renderOnline} +
    +
    + ); + } +}; +``` + +
    + + +### After Test +
    + +```js +console.info('after the test'); +``` + +
    + +
    + +## Solution +
    + + +```js +class MyComponent extends React.Component { + constructor(props) { + super(props); + this.state = { + users: [ + { + username: 'Jeff', + online: true + }, + { + username: 'Alan', + online: false + }, + { + username: 'Mary', + online: true + }, + { + username: 'Jim', + online: false + }, + { + username: 'Sara', + online: true + }, + { + username: 'Laura', + online: true + } + ] + } + } + render() { + const usersOnline = this.state.users.filter(user => { + return user.online; + }); + const renderOnlineUsers = usersOnline.map(user => { + return ( +
  • {user.username}
  • + ); + }); + return ( +
    +

    Current Online Users:

    +
      + {renderOnlineUsers} +
    +
    + ); + } +}; +``` + +
    diff --git a/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.map-to-dynamically-render-elements.spanish.md b/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.map-to-dynamically-render-elements.spanish.md new file mode 100644 index 0000000000..f2b7435447 --- /dev/null +++ b/curriculum/challenges/spanish/03-front-end-libraries/react/use-array.map-to-dynamically-render-elements.spanish.md @@ -0,0 +1,162 @@ +--- +id: 5a24c314108439a4d403618a +title: Use Array.map() to Dynamically Render Elements +localeTitle: Utilice Array.map () para generar elementos dinámicamente +challengeType: 6 +isRequired: false +--- + +## Description +
    +La representación condicional es útil, pero es posible que necesite que sus componentes representen un número desconocido de elementos. A menudo, en programación reactiva, un programador no tiene forma de saber cuál es el estado de una aplicación hasta el tiempo de ejecución, ya que mucho depende de la interacción de un usuario con ese programa. Los programadores deben escribir su código para manejar correctamente ese estado desconocido antes de tiempo. Usar Array.map() en React ilustra este concepto. +Por ejemplo, creas una aplicación simple "Lista de tareas pendientes". Como programador, no tiene forma de saber cuántos elementos puede tener un usuario en su lista. Debe configurar su componente para que muestre dinámicamente el número correcto de elementos de la lista mucho antes de que alguien que usa el programa decida que hoy es el día de la lavandería. +
    + +## Instructions +
    +El editor de código tiene la mayoría del componente MyToDoList configurado. Parte de este código debe parecer familiar si completó el desafío del formulario controlado. Notará un área de textarea y un button , junto con un par de métodos que rastrean sus estados, pero todavía no se muestra nada en la página. +Dentro del constructor , cree un objeto this.state y defina dos estados: userInput debe inicializarse como una cadena vacía, y toDoList debe inicializarse como una matriz vacía. A continuación, elimine el comentario en el método render() junto a la variable de items . En su lugar, toDoList sobre la matriz toDoList almacenada en el estado interno del componente y toDoList dinámicamente un li para cada elemento. Intente ingresar la cadena eat, code, sleep, repeat en el área de textarea , luego haga clic en el botón y vea qué sucede. +Nota: Es posible que sepa que todos los elementos secundarios de hermanos creados por una operación de mapeo como esta deben suministrarse con un atributo de key único. No te preocupes, este es el tema del próximo reto. +
    + +## Tests +
    + +```yml +tests: + - text: El componente MyToDoList debería existir y representarse en la página. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").length === 1; })(), "The MyToDoList component should exist and render to the page.");' + - text: El primer elemento secundario de MyToDoList debe ser un elemento textarea . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").children().childAt(0).type() === "textarea"; })(), "The first child of MyToDoList should be a textarea element.");' + - text: El tercer elemento secundario de MyToDoList debe ser un elemento button . + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); return mockedComponent.find("MyToDoList").children().childAt(2).type() === "button"; })(), "The third child of MyToDoList should be a button element.");' + - text: El estado de MyToDoList se debe inicializar con toDoList como una matriz vacía. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return Array.isArray(initialState.toDoList) === true && initialState.toDoList.length === 0; })(), "The state of MyToDoList should be initialized with toDoList as an empty array.");' + - text: El estado de MyToDoList se debe inicializar con userInput como una cadena vacía. + testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const initialState = mockedComponent.state(); return typeof initialState.userInput === "string" && initialState.userInput.length === 0; })(), "The state of MyToDoList should be initialized with userInput as an empty string.");' + - text: 'Cuando se hace clic en el botón Crear lista , el componente MyToDoList debería devolver dinámicamente una lista desordenada que contenga un elemento de elemento de lista para cada elemento de una lista separada por comas ingresada en el elemento textarea . ' + testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 100)); const mockedComponent = Enzyme.mount(React.createElement(MyToDoList)); const simulateChange = (el, value) => el.simulate("change", {target: {value}}); const state_1 = () => { return waitForIt(() => mockedComponent.find("ul").find("li"))}; const setInput = () => { return waitForIt(() => simulateChange(mockedComponent.find("textarea"), "testA, testB, testC"))}; const click = () => { return waitForIt(() => mockedComponent.find("button").simulate("click"))}; const state_2 = () => { return waitForIt(() => { const nodes = mockedComponent.find("ul").find("li"); return { nodes, text: nodes.reduce((t, n) => t + n.text(), "") }; })}; const setInput_2 = () => { return waitForIt(() => simulateChange(mockedComponent.find("textarea"), "t1, t2, t3, t4, t5, t6"))}; const click_1 = () => { return waitForIt(() => mockedComponent.find("button").simulate("click"))}; const state_3 = () => { return waitForIt(() => { const nodes = mockedComponent.find("ul").find("li"); return { nodes, text: nodes.reduce((t, n) => t + n.text(), "") }; })}; const awaited_state_1 = await state_1(); const awaited_setInput = await setInput(); const awaited_click = await click(); const awaited_state_2 = await state_2(); const awaited_setInput_2 = await setInput_2(); const awaited_click_1 = await click_1(); const awaited_state_3 = await state_3(); assert(awaited_state_1.length === 0 && awaited_state_2.nodes.length === 3 && awaited_state_3.nodes.length === 6 && awaited_state_2.text === "testA testB testC" && awaited_state_3.text === "t1 t2 t3 t4 t5 t6", "When the Create List button is clicked, the MyToDoList component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the textarea element."); }; ' + +``` + +
    + +## Challenge Seed +
    + +
    + +```jsx +const textAreaStyles = { + width: 235, + margin: 5 +}; + +class MyToDoList extends React.Component { + constructor(props) { + super(props); + // change code below this line + + // change code above this line + this.handleSubmit = this.handleSubmit.bind(this); + this.handleChange = this.handleChange.bind(this); + } + handleSubmit() { + const itemsArray = this.state.userInput.split(','); + this.setState({ + toDoList: itemsArray + }); + } + handleChange(e) { + this.setState({ + userInput: e.target.value + }); + } + render() { + const items = null; // change code here + return ( +
    +