diff --git a/README.es.md b/README.es.md index 2b5a0b9d..1e010a68 100644 --- a/README.es.md +++ b/README.es.md @@ -1,75 +1,191 @@ -# Tutorial & Ejercicios de arrays y ciclos en JavaScript - +
- - +# Ejercicios de arrays y loops de Javascript interactivos -> Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors) de [4Geeks Academy](https://4geeksacademy.co/) +Portada del tutorial: las palabras Learn Javascript, Loops and Arrays, interactive, junto al logo hexagonal amarillo de JavaScript -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +[![Tutorial certificado](https://img.shields.io/badge/4Geeks_Academy-Tutorial_certificado-2563eb)](https://4geeks.com/es/interactive-exercise/javascript-array-loops-exercises-es) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-43_ejercicios_autocorregidos-2563eb)](https://github.com/learnpack/learnpack) +[![Abrir en GitHub Codespaces](https://img.shields.io/badge/Abrir_en-GitHub_Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial) +Estas instrucciones también están [🇬🇧 en inglés](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/blob/HEAD/README.md) + +
-¡Docenas de ejercicios de arrays o [arreglos en javascript](https://4geeks.com/es/lesson/array-arreglo-en-javascript) y loops para mejorar tus habilidades: for, forEach, mapear, filtrar, hacer un loop a un objeto, hacer un loop en arrays bidimensionales, agregar condiciones a los loops, encontrar un elemento y mucho más! +Este tutorial reúne 44 ejercicios de JavaScript sobre arrays y bucles: una pantalla de bienvenida y 43 retos que se corrigen solos con Jest sobre Node.js. Practicarás `for`, `for...of`, `for...in`, `do...while`, `forEach`, `map` y `filter` con datos reales: matrices, objetos literales y arrays de objetos. Dura unas 12 horas, arranca desde `console.log()` y 17 ejercicios traen vídeo con la solución. -
    -
  1. JavaScript para Principiantes
  2. -
  3. Looping con JavaScript ← 🔥 Estás aquí
  4. -
  5. Funciones de JavaScript
  6. -
  7. Master JavaScript
  8. -
+## 📋 Ficha del tutorial + +- **Dificultad:** fácil, pensado para quien nunca ha escrito un bucle. +- **Duración estimada:** 12 horas. +- **Tecnologías:** JavaScript, arrays, Node.js. +- **Ejercicios:** 44 carpetas, 43 de ellas con fichero de test. +- **Corrección:** automática, con Jest 29.7.0 y `rewire` para leer tus variables. +- **Vídeos de solución:** 17 ejercicios enlazan un vídeo explicativo. +- **Idiomas:** cada ejercicio trae instrucciones en español y en inglés. + -¡Te necesitamos! Estos ejercicios se crean y mantienen con colaboradores como tú. Si encuentras algún error o falta de ortografía, contribuye o infórmanos. +## 🎯 ¿Qué vas a aprender? +El tutorial recorre toda la caja de herramientas de los bucles en JavaScript, con una idea pequeña por ejercicio: -## Instalación en un clic (recomendado) +- **Anatomía de un array:** los elementos, el `length` y los índices que empiezan en cero, además de leer y sustituir un valor por su posición. +- **El `for` de toda la vida:** recorrer hacia delante, hacia atrás, saltando de dos en dos y empezando por la mitad del array. +- **Condicionales dentro del bucle:** imprimir solo lo que cumple una condición, contar apariciones y acumular en variables auxiliares. +- **`do...while`:** el bucle que siempre se ejecuta al menos una vez, aplicado a una cuenta atrás que termina en `LIFTOFF`. +- **`for...of` y `for...in`:** acceso directo a los valores y recorrido de las propiedades de un objeto literal. +- **`forEach`:** iterar por efecto secundario, cuando el valor devuelto no importa. +- **`map`:** seis ejercicios dedicados (del 20.1 al 20.6) para transformar un array en otro del mismo tamaño. +- **`filter`:** quedarte solo con los elementos que cumplen una condición, incluidos arrays de objetos. +- **Arrays bidimensionales:** bucles anidados sobre matrices, coordenadas y el plano de un aparcamiento. -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). +![Diagrama de un array de longitud 8: ocho casillas numeradas donde las etiquetas señalan las posiciones (índices del 0 al 7) y los elementos guardados en cada posición](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/DbmSOHT.png) -> Una vez ya tengas abierto VSCode los ejercicios de LearnPack deberían empezar automáticamente, si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` +## 👀 ¿Qué vas a construir? -## Instalación local +Cada ejercicio es un programa diminuto que completas dentro de `app.js`. Estos son algunos de los reales: -Clona el repositorio en tu ambiente local y sigue los siguientes pasos: +- **`07.1` Finding Waldo:** recorrer un array de 250 nombres e imprimir la posición donde se esconde `"Waldo"`, comparando con `toLowerCase()` para que dé igual si va en mayúsculas. +- **`07.2` Letter Counter:** recorrer un párrafo entero y rellenar un objeto `counts` donde cada letra es una clave y su valor es cuántas veces aparece, del estilo `{ h: 1, e: 1, l: 3, o: 2 }`, ignorando espacios y mayúsculas. +- **`11` DO DO DO:** contar de 20 a 1 con `do...while`, añadir un `!` a cada múltiplo de 5 e imprimir `LIFTOFF` en lugar del `0`. +- **`14` Divide and Conquer:** escribir `mergeTwoList()` para que `[1,2,33,10,20,4]` se convierta en `[1, 33, 2, 10, 20, 4]`, primero los impares. +- **`19` And one and two and three:** recorrer las propiedades de un objeto `contact` e imprimir líneas del estilo `fullName : John Doe`. +- **`22` Matrix Builder:** escribir `matrixBuilder(5)` para que devuelva una matriz de 5x5 rellena de ceros y unos aleatorios. +- **`23` Parking Lot:** escribir `getParkingLotState()`, que recibe cualquier matriz y devuelve `{ totalSlots, availableSlots, occupiedSlots }`. +- **`24` Making a UL:** encadenar `filter`, `map` y `forEach` sobre un array de objetos de colores para montar una única cadena ``. +- **`25` Techno Beats:** escribir `lyricsGenerator()` para que `[0,0,1,1,0,0,0]` se convierta en `"Boom Boom Drop the bass Drop the bass Boom Boom Boom"`, añadiendo `!!!Break the bass!!!` cuando aparecen tres `1` seguidos. -1. Instala LearnPack, el package manager para los tutoriales interactivos y el node compiler plugin para LearnPack, asegúrate también de tener node.js 14+: +![Esquema de un aparcamiento: el dibujo del parking junto al mismo parking representado como una rejilla de números, donde 1 significa ocupado, 2 significa libre y 0 significa que ahí no hay plaza](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/23.png) -```bash -$ npm i @learnpack/learnpack -g -``` +## 🎓 ¿Qué necesitas antes de empezar? + +- **Sintaxis básica de JavaScript:** variables, condicionales `if` y cómo se declara una función. El ejercicio `01` arranca en `console.log()`, así que no se da por sabido nada más. +- **Nada instalado si usas Codespaces:** el contenedor ya trae Node.js 22, Jest y la CLI de LearnPack listos. +- **Node.js solo si trabajas en local:** los ejercicios se ejecutan en Node, aquí no hay navegador ni DOM. +- **Ninguna experiencia previa con bucles:** la anatomía del array, los índices y el primer `for` se explican dentro del propio tutorial. +- **Nada de inglés:** los 44 ejercicios traen las instrucciones en español y en inglés, y el selector de banderas del menú cambia de idioma sin que pierdas tu progreso. + +## ✅ ¿Cómo funciona la corrección automática? + +43 de los 44 ejercicios tienen fichero de test (23 se llaman `test.js` y 20 `tests.js`); solo `00-Welcome`, la pantalla de bienvenida, no tiene. Al pulsar `Run`, la CLI de LearnPack ejecuta ese fichero con Jest y te dice qué comprobación ha fallado. + +Los tests miran tres cosas distintas, y saber cuál está fallando te ahorra mucho tiempo: + +1. **Lo que imprimes por consola.** `console.log` está simulado: cada llamada se guarda en un búfer y luego se compara con el resultado esperado. + +2. **El código fuente de tu `app.js`.** Algunos ejercicios leen el fichero como texto y lo pasan por una expresión regular, así que el `09` exige literalmente `.forEach(` y el `07.1` exige tanto `for (` como `.toLowerCase(`. + +3. **Tus variables y funciones, por su nombre.** Los tests cargan `app.js` con `rewire` y sacan valores de dentro, de modo que `deletePerson`, `matrixBuilder`, `resultingNames` o `coordinatesArray` deben conservar el nombre exacto que traen de fábrica. + +> 💡 La corrección es estricta a propósito, pero es una guía, no un juez. Si te atascas, abre el menú de ejercicios, salta al siguiente y vuelve más tarde. + +## 💡 ¿Qué errores conviene evitar? + +1. **Imprimir cuando el ejercicio espera un `return`.** En el `25` Techno Beats el test llama a `lyricsGenerator([1,1,1])` y comprueba que lo devuelto sea la cadena `"Drop the bass Drop the bass Drop the bass !!!Break the bass!!!"`. Si terminas la función con `console.log(beats)` en vez de `return beats`, la función devuelve `undefined` y la comprobación falla. En el `12`, el `22` y el `23` pasa lo mismo: las llamadas a `console.log` ya vienen escritas al final del `app.js` y lo único que tienes que hacer es devolver el valor. + +2. **Dejarte `console.log` de depuración.** Hay tests que cuentan las llamadas exactas: el `12` Delete element espera 3 y el `25` Techno Beats espera 5. Un print de más pone en rojo una solución correcta. + +3. **Resolverlo con un método distinto al que se está enseñando.** Como los tests rebuscan en tu código fuente, cambiar el `forEach` del ejercicio `09` por un `for` falla aunque la salida por consola sea idéntica, y el `14` Divide and Conquer solo pasa si la palabra `concat` aparece en tu fichero. + +4. **Renombrar o borrar las variables que vienen dadas.** `rewire` las busca por su nombre, así que si el `21` Filter an Array deja de declarar `resultingNames`, ya falla la primera comprobación. + +5. **Escribir la respuesta a mano en vez de calcularla.** El `23` Parking Lot se corrige con dos matrices distintas, una de 4x4 y otra de 4x6, así que un `getParkingLotState()` que devuelva números fijos pasa la primera comprobación y suspende la segunda. Al `22` Matrix Builder solo se le llama con `matrixBuilder(5)`, pero el test exige que la matriz contenga a la vez `0` y `1`, así que rellenarla con un único valor también falla. + +6. **Modificar el array que te dan.** El ejercicio `15` comprueba que `myArray[14]` siga valiendo `5435` después de ejecutar tu código, así que ordenar el array original en el sitio suspende aunque el máximo que imprimes sea correcto. + +7. **Confundir los tipos.** El `02.1` pide el valor `null`, no la cadena `"null"`, y el `10` Everything is awesome quiere que metas el número `1`, no `"1"`. + +## ❓ Preguntas frecuentes + +### ¿Hace falta instalar algo para empezar? + +No. Al abrir el repositorio en GitHub Codespaces se levanta un contenedor que instala solo Node.js 22, Jest 29.7.0 y la CLI de LearnPack, y los ejercicios se abren automáticamente dentro de VS Code. La instalación local es opcional y solo necesita Node.js y un comando de `npm`. -2. Inicia el tutorial/ejercicios ejecutando el siguiente comando en el mismo nivel donde se encuentra tu archivo learn.json: +### ¿Cuánto se tarda en terminar los 44 ejercicios? + +La estimación es de 12 horas. La primera mitad (del `01` al `08.3`) son ejercicios cortos de unos pocos minutos; los últimos, como Matrix Builder, Making a UL o Techno Beats, son pequeños algoritmos que pueden llevarte media hora o más. + +### ¿Y si el test falla pero mi resultado parece correcto? + +Fíjate en cuál de las comprobaciones ha fallado. Muchos tests comparan el búfer de la consola carácter a carácter, así que un espacio de más, un salto de línea que falta o un `console.log` extra bastan para suspender. Otros revisan el código fuente buscando un método concreto, o buscan una función por su nombre exacto. + +### ¿Puedo usar un `for` en lugar de `map` o `filter`? + +En los ejercicios que van justo de esos métodos, no. Los tests del `09`, el `10` y el `16` buscan `forEach` dentro de tu `app.js`, y los de `map` y `filter` comparan tu resultado con el del método correspondiente. En el resto puedes elegir el bucle que prefieras. + +### ¿Hay soluciones que pueda consultar? + +Sí. Cada una de las 43 carpetas con test incluye un `solution.hide.js` con una implementación que funciona, y 17 ejercicios enlazan además un vídeo desde el encabezado de sus instrucciones. Intenta terminarlo por tu cuenta primero: los tests te dan mucha más información que la solución. + +### ¿Cuesta algo y de quién es el código que escribo? + +Acceder a este repositorio y a sus ejercicios no cuesta nada, y el código que escribes en `app.js` es tuyo. El contenido del tutorial, en cambio, no es open source: se publica con todos los derechos de propiedad intelectual reservados, así que no está permitido republicarlo ni redistribuirlo. Puedes leer el texto completo en [LICENSE.md](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/blob/HEAD/LICENSE.md). + + +## 📚 Tutoriales relacionados + +Este paquete es el segundo paso de la serie interactiva de JavaScript: + +1. [JavaScript para principiantes](https://4geeks.com/es/interactive-exercise/ejercicios-javascript-para-principiantes) +2. **Arrays y loops** ← estás aquí +3. [Funciones de JavaScript](https://4geeks.com/es/interactive-exercise/javascript-functions-exercises-tutorial-es) +4. [Domina JavaScript practicando](https://4geeks.com/es/interactive-exercise/master-javascript-exercises-es) + +## 🚀 Cómo empezar + +La vía rápida es [abrirlo en GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial). El contenedor instala todo y los ejercicios arrancan solos dentro de VS Code. + +Si no arrancan automáticamente, escribe esto en la terminal: ```bash -$ learnpack start +learnpack start ``` -Si tienes algún problema o quieres saber más, puedes referirte a la documentación de [cómo empezar con learnpack](https://4geeks.com/docs/learnpack/paso-a-paso-learnpack-para-estudiantes). +También puedes abrir el paquete en [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). - +Para moverte entre ejercicios usa el menú superior, que además lleva la cuenta de cuántos de los 44 llevas resueltos: + +![Menú de ejercicios de LearnPack abierto, con la lista del 00 Welcome al 03 Print_the_last_one, el contador 0/44 Solved exercises y el selector de idioma con banderas](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/exercises-menu.png) + +## 💻 Instalación local -## ¿Cómo están organizados los ejercicios de arrays? +Clona el repositorio y sigue estos pasos: -Cada ejercicio es una pequeña aplicación de React que contiene los siguientes archivos: +1. Instala LearnPack y su plugin compilador de Node.js. Necesitas tener Node.js instalado antes: -1. **app.js**: Representa el archivo JavaScript de entrada que ejecutará la computadora. -2. **README.md**: Contiene las instrucciones de ejercicio. -3. **test.js**: Contiene el script del test para el ejercicio (no es necesario que abras este archivo). + ```bash + npm i @learnpack/learnpack -g + learnpack plugins:install @learnpack/node + ``` -> Nota: Estos ejercicios tienen calificación automática. Los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. +2. Arranca el tutorial desde la misma carpeta donde está el `learn.json`: -## Colaboradores - -Gracias a estas maravillosas personas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + ```bash + learnpack start + ``` -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 🤓 (build-tutorial) ✅ (documentación) 📖 +Si algo se tuerce, la [guía de inicio de LearnPack para estudiantes](https://4geeks.com/docs/learnpack/quickstart-for-learners) cubre todo el proceso. -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 +## 📝 Cómo están organizados los ejercicios -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! +Cada carpeta de reto dentro de `exercises/` es un pequeño programa de Node.js con estos ficheros: -Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). +- **`app.js`:** el fichero que editas. Es el punto de entrada que se ejecuta. +- **`README.md`:** las instrucciones en inglés. +- **`README.es.md`:** las mismas instrucciones en español. +- **`test.js` o `tests.js`:** el test de Jest que corrige tu solución. No hace falta que lo abras. +- **`solution.hide.js`:** una solución que funciona, oculta por LearnPack hasta que la pidas. + +## 🤝 Colaboradores + +Gracias a estas personas ([leyenda de emojis](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr): programación 💻, idea 🤔, tests ⚠️, revisión de pull requests 👀, construcción del tutorial ✅, documentación 📖 + +2. [Paolo (plucodev)](https://github.com/plucodev): reporte de bugs 🐛, programación 💻, traducción 🌎 + +Puedes ver la lista completa en el [gráfico de colaboradores](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors). El proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors) y toda contribución es bienvenida. Si encuentras un error o una errata, repórtalo o manda un pull request. + diff --git a/README.md b/README.md index a60203fb..101f9546 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,191 @@ -# Looping in JavaScript Tutorial & Exercises - +
- - +# Learn Javascript Arrays and Loops Interactive -> By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors) at [4Geeks Academy](https://4geeksacademy.co/) +Tutorial cover: the words Learn Javascript, Loops and Arrays, interactive, next to the yellow JavaScript hexagon logo -![last commit](https://img.shields.io/github/last-commit/4geeksacademy/javascript-arrays-exercises-tutorial) -[![build by developers](https://img.shields.io/badge/build_by-Developers-blue)](https://breatheco.de) -[![build by developers](https://img.shields.io/twitter/follow/4geeksacademy?style=social&logo=twitter)](https://twitter.com/4geeksacademy) +[![Certified tutorial](https://img.shields.io/badge/4Geeks_Academy-Certified_tutorial-2563eb)](https://4geeks.com/en/interactive-exercise/javascript-array-loops-exercises) +[![Autograded with LearnPack](https://img.shields.io/badge/LearnPack-43_autograded_exercises-2563eb)](https://github.com/learnpack/learnpack) +[![Open in GitHub Codespaces](https://img.shields.io/badge/Open_in-GitHub_Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial) -*Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/blob/master/README.es.md) :es:* +Read these instructions in [🇪🇸 Spanish](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/blob/HEAD/README.es.md) + +
-Dozens of looping exercises to sharpen your looping skills with for, forEach, map, filter, looping an object, looping bidimentional arrays, adding conditions to loops, finding an element, and more! +This tutorial contains 44 JavaScript exercises about arrays and loops: one welcome screen plus 43 challenges that are graded automatically by Jest on Node.js. You practice `for`, `for...of`, `for...in`, `do...while`, `forEach`, `map` and `filter` against real data such as matrices, object literals and arrays of objects. It takes about 12 hours, starts from `console.log()`, and 17 exercises ship with a recorded video solution. -## Before you start... some related tutorials: -
    -
  1. JavaScript for Beginners
  2. -
  3. Looping with JavaScript ← 🔥 You are here
  4. -
  5. JavaScript Functions
  6. -
  7. Master JavaScript
  8. -
+## 📋 About this tutorial + +- **Difficulty:** easy, designed for people who have never written a loop. +- **Estimated duration:** 12 hours. +- **Technologies:** JavaScript, arrays, Node.js. +- **Exercises:** 44 folders, 43 of them with an automated test file. +- **Grading:** automatic, Jest 29.7.0 plus `rewire` to inspect your variables. +- **Video solutions:** 17 exercises include a linked walkthrough video. +- **Languages:** every exercise ships with instructions in English and Spanish. + -> We need you! These exercises are built and maintained in collaboration with contributors such as yourself. If you find any bugs or misspellings, please contribute and/or report them. +## 🎯 What will you learn? +The tutorial walks the whole looping toolbox in JavaScript, one small idea per exercise: -## One click installation (recommended): +- **Array anatomy:** items, `length` and zero-based indexes, plus reading and replacing a value by position. +- **The classic `for` loop:** counting up, counting down, jumping two positions at a time, and starting from the middle of an array. +- **Conditionals inside loops:** printing only what matches, counting occurrences, and accumulating into helper variables. +- **`do...while`:** the loop that always runs at least once, used for a countdown that ends in `LIFTOFF`. +- **`for...of` and `for...in`:** direct access to values, and iterating the properties of an object literal. +- **`forEach`:** side-effect iteration where the return value is ignored. +- **`map`:** six dedicated exercises (20.1 to 20.6) that transform one array into another of the same length. +- **`filter`:** keeping only the elements that satisfy a condition, including arrays of objects. +- **Two-dimensional arrays:** nested loops over matrices, coordinates and a parking-lot grid. -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). +![Diagram of an array with length 8: eight numbered boxes where the labels point to the positions (indexes 0 to 7) and to the items stored in each position](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/DbmSOHT.png) -> Once you have opened VSCode, the LearnPack exercises should start automatically. If exercises don't run automatically, you can try typing on your terminal: `$ learnpack start` +## 👀 What will you build? -## Local Installation +Every exercise is a tiny program you complete inside `app.js`. These are some of the real ones: -Clone the repository in your local environment and follow the steps below: +- **`07.1` Finding Waldo:** loop an array of 250 names and print the position where `"Waldo"` is hiding, comparing with `toLowerCase()` so casing does not matter. +- **`07.2` Letter Counter:** loop a whole paragraph and fill a `counts` object where every letter is a key and its value is how many times it appears, like `{ h: 1, e: 1, l: 3, o: 2 }`, ignoring spaces and casing. +- **`11` DO DO DO:** count down from 20 to 1 with `do...while`, add a `!` to every multiple of 5, and print `LIFTOFF` instead of `0`. +- **`14` Divide and Conquer:** write `mergeTwoList()` so `[1,2,33,10,20,4]` becomes `[1, 33, 2, 10, 20, 4]`, odd numbers first. +- **`19` And one and two and three:** loop the properties of a `contact` object and print `fullName : John Doe` style lines. +- **`22` Matrix Builder:** write `matrixBuilder(5)` that returns a 5x5 matrix filled with random `0` and `1` values. +- **`23` Parking Lot:** write `getParkingLotState()` that receives any matrix and returns `{ totalSlots, availableSlots, occupiedSlots }`. +- **`24` Making a UL:** chain `filter`, `map` and `forEach` over an array of colour objects to build a single `` string. +- **`25` Techno Beats:** write `lyricsGenerator()` that turns `[0,0,1,1,0,0,0]` into `"Boom Boom Drop the bass Drop the bass Boom Boom Boom"`, adding `!!!Break the bass!!!` when three `1` appear in a row. -1. Install LearnPack, the package manager for learning tutorials and the node compiler plugin for LearnPack, make sure you also have node.js 14+: +![Parking lot diagram: a drawing of a parking lot next to the same lot represented as a grid of numbers, where 1 means occupied, 2 means available and 0 means it is not a parking spot](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/23.png) -```bash -$ npm i @learnpack/learnpack -g -``` +## 🎓 What do you need before starting? + +- **Basic JavaScript syntax:** variables, `if` conditionals and how to declare a function. Exercise `01` starts at `console.log()`, so nothing beyond that is assumed. +- **No local setup if you use Codespaces:** the dev container already installs Node.js 22, Jest and the LearnPack CLI for you. +- **Node.js only if you run it locally:** the exercises run on Node, there is no browser or DOM involved. +- **No prior experience with loops:** the array anatomy, indexes and the first `for` loop are all taught inside the tutorial. +- **No English required:** all 44 exercises ship with instructions in English and Spanish, and the flag selector in the menu switches between them without losing your progress. + +## ✅ How does the automatic grading work? + +43 of the 44 exercises have a test file (23 named `test.js` and 20 named `tests.js`); only `00-Welcome`, the intro screen, has none. When you click `Run` the LearnPack CLI executes that file with Jest and shows you which assertion failed. + +The tests check three different things, and knowing which one is failing saves a lot of time: + +1. **The output printed to the console.** `console.log` is mocked and every call is stored in a buffer, then compared against the expected result. + +2. **The source code of your `app.js`.** Some exercises read the file as text and match it against a regular expression, so exercise `09` literally requires `.forEach(` and exercise `07.1` requires both `for (` and `.toLowerCase(`. + +3. **Your variables and functions by name.** The tests load `app.js` with `rewire` and pull values out of it, so `deletePerson`, `matrixBuilder`, `resultingNames` or `coordinatesArray` must keep the exact name given in the starter file. + +> 💡 The grading is strict on purpose, but it is a guide, not a judge. If you are stuck, open the exercise menu, jump ahead and come back later. + +## 💡 What mistakes should you avoid? + +1. **Printing when the exercise expects a `return`.** In `25` Techno Beats the test calls `lyricsGenerator([1,1,1])` and asserts that the returned value is the string `"Drop the bass Drop the bass Drop the bass !!!Break the bass!!!"`. If you end the function with `console.log(beats)` instead of `return beats`, the function returns `undefined` and the assertion fails. It is the same story in `12`, `22` and `23`: the `console.log` calls are already written at the bottom of `app.js` and your only job is to return the value. + +2. **Leaving debugging `console.log` calls behind.** Some tests count the calls exactly: `12` Delete element expects exactly 3 and `25` Techno Beats expects exactly 5. One extra print turns a correct solution red. + +3. **Solving it with a different method than the one being taught.** Because the tests grep your source code, replacing the `forEach` of exercise `09` with a `for` loop fails even though the console output is identical, and `14` Divide and Conquer only passes if the word `concat` appears in your file. + +4. **Renaming or removing the variables that come with the exercise.** `rewire` looks them up by name, so if `21` Filter an Array no longer declares `resultingNames`, the very first assertion breaks. + +5. **Hardcoding the answer instead of computing it.** `23` Parking Lot is graded with two different matrices, a 4x4 one and a 4x6 one, so a `getParkingLotState()` that returns fixed numbers passes the first assertion and fails the second. `22` Matrix Builder is only called as `matrixBuilder(5)`, but the test still demands that the matrix contain both `0` and `1`, so filling it with a single value fails too. + +6. **Mutating the array you were given.** Exercise `15` asserts that `myArray[14]` is still `5435` after your code runs, so sorting the original array in place fails the test even if the maximum you print is right. + +7. **Confusing types.** `02.1` asks for the value `null`, not the string `"null"`, and `10` Everything is awesome wants the number `1` pushed, not `"1"`. + +## ❓ Frequently asked questions + +### Do I need to install anything to start? + +No. Opening the repository in GitHub Codespaces gives you a container that installs Node.js 22, Jest 29.7.0 and the LearnPack CLI automatically, and the exercises open by themselves inside VS Code. Installing locally is optional and only needs Node.js plus one `npm` command. + +### How long does it take to finish the 44 exercises? -2. Start the tutorial/exercises by running the following command at the same level where your learn.json file is: +The tutorial is estimated at 12 hours. The first half (exercises `01` to `08.3`) is mostly short drills of a few minutes each; the last ones, such as Matrix Builder, Making a UL and Techno Beats, are small algorithms that can take 30 minutes or more. + +### What if the test fails but my output looks correct? + +Read which of the assertions failed. Many tests compare the console buffer character by character, so an extra space, a missing line break or an extra `console.log` is enough to fail. Others check the source code for a specific method, or look for a function by its exact name. + +### Can I use a `for` loop instead of `map` or `filter`? + +Not in the exercises that are specifically about those methods. The tests of `09`, `10` and `16` search your `app.js` for `forEach`, and the `map` and `filter` exercises compare your result against the output of the corresponding method. Everywhere else you are free to pick the loop you prefer. + +### Is there a solution I can look at? + +Yes. Each of the 43 graded folders contains a `solution.hide.js` file with a working implementation, and 17 exercises also link a video walkthrough from the top of their instructions. Try to finish the exercise first; the tests give you far more feedback than the solution does. + +### Does it cost anything, and who owns the code I write? + +Access to this repository and its exercises costs nothing, and the code you write in `app.js` is yours. The tutorial content itself is not open source: it is published under reserved intellectual property terms, so republishing or redistributing it is not allowed. Read the full text in [LICENSE.md](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/blob/HEAD/LICENSE.md). + + +## 📚 Related tutorials + +This package is the second step of the interactive JavaScript series: + +1. [JavaScript for Beginners](https://4geeks.com/en/interactive-exercise/javascript-beginner-exercises) +2. **Arrays and Loops** ← you are here +3. [JavaScript Functions](https://4geeks.com/en/interactive-exercise/javascript-functions-exercises-tutorial) +4. [Master JavaScript Practicing](https://4geeks.com/en/interactive-exercise/master-javascript-exercises) + +## 🚀 How to start + +The fastest way is [Open in GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/javascript-arrays-exercises-tutorial). The container installs everything and the exercises start on their own inside VS Code. + +If they do not start automatically, run this in the terminal: ```bash -$ learnpack start +learnpack start ``` -If you encounter any issues or want to learn more about starting a tutorial with learnpack, you can read the [learnpack quickstart](https://4geeks.com/docs/learnpack/quickstart-for-learners) documentation here. +You can also open the package in [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial). - +To move between exercises, use the top menu. It also shows how many of the 44 exercises you have solved so far: -## How are the exercises organized? +![LearnPack exercise menu open, listing the exercises from 00 Welcome to 03 Print_the_last_one with a 0/44 solved exercises counter and a language flag selector](https://raw.githubusercontent.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/master/.learn/assets/exercises-menu.png) -Each exercise is a small React application containing the following files: +## 💻 Local installation -1. **app.js:** represents the entry JavaScript file that will be executed by the computer. -2. **README.md:** contains exercise instructions. -3. **test.js:** contains the testing script for the exercise (you don't have to open this file). +Clone the repository and follow these steps: -> Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. +1. Install LearnPack and its Node.js compiler plugin. You need Node.js installed first: -## Contributors + ```bash + npm i @learnpack/learnpack -g + learnpack plugins:install @learnpack/node + ``` -Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +2. Start the tutorial from the same folder where `learn.json` lives: + + ```bash + learnpack start + ``` + +If you run into trouble, the [LearnPack quickstart for learners](https://4geeks.com/docs/learnpack/quickstart-for-learners) covers the whole setup. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻 (idea) 🤔, (build-tests) ⚠️ , (pull-request-review) 👀 (build-tutorial) ✅ (documentation) 📖 +## 📝 How the exercises are organized -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 +Each challenge folder inside `exercises/` is one small Node.js program with these files: -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! +- **`app.js`:** the file you edit. It is the entry point that gets executed. +- **`README.md`:** the instructions in English. +- **`README.es.md`:** the same instructions in Spanish. +- **`test.js` or `tests.js`:** the Jest test that grades your solution. You do not need to open it. +- **`solution.hide.js`:** a working solution, hidden by LearnPack until you ask for it. -This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by [Alejandro Sánchez](https://twitter.com/alesanchezr) and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer), and [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). +## 🤝 Contributors + +Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): + +1. [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr): coder 💻, idea 🤔, build-tests ⚠️, pull-request-review 👀, build-tutorial ✅, documentation 📖 + +2. [Paolo (plucodev)](https://github.com/plucodev): bug reports 🐛, coder 💻, translation 🌎 + +See the full list on the [contributors graph](https://github.com/4GeeksAcademy/javascript-arrays-exercises-tutorial/graphs/contributors). This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification, and contributions of any kind are welcome. If you find a bug or a typo, please report it or send a pull request. +