diff --git a/exercises/21-Russian_Roulette/README.es.md b/exercises/21-Russian_Roulette/README.es.md deleted file mode 100644 index 2486da28..00000000 --- a/exercises/21-Russian_Roulette/README.es.md +++ /dev/null @@ -1,19 +0,0 @@ -# `21` Russian Roulette - -¿Alguna vez has jugado a la Ruleta Rusa? ¡Es muy divertido! Si logras sobrevivir... (muajajajajaja). - -El revólver sólo tiene 6 récamaras para balas. Tú insertas una bala en uno de las recámaras, y giras las recámaras del revólver para hacer el juego aleatorio. Nadie sabe la posición de la bala ¡¡¡FUEGO!!!....... ¿has muerto? - -## 📝 Instrucciones: - -El juego casi está funcionando. - -1. Completa la función `fireGun()` para que el juego funcione. Debes comparar la posición de la bala contra la posición de la recámara. - -## 💡 Pistas: - -+ Si la posición de la bala `firePosition` coincide con la posición de la recámara dada por la función `spinChamber`, la función `fireGun()` debe devolver `You're dead!`. - -+ Si la posición de la bala `firePosition` no coincide con la posición de la recámara dada por la función `spinChamber`, la función `fireGun()` debe devolver `Keep playing!`. - -+ La función `spinChamber` retorna un número entero aleatorio entre 1 y 6. diff --git a/exercises/21-Russian_Roulette/README.md b/exercises/21-Russian_Roulette/README.md deleted file mode 100644 index 9d9f1b9a..00000000 --- a/exercises/21-Russian_Roulette/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# `21` Russian Roulette - -Have you ever played Russian Roulette? It's super fun! If you make it (wuuuahahahaha). - -Revolvers can have 6 chambers for bullets. A single bullet is inserted into one of the chambers. The revolver chambers are spun to make the game random. Nobody knows the position of the bullet. FIRE!!!....... Are you dead? - -## 📝 Instructions: - -The game is almost working. - -1. The `fireGun()` function needs to be completed to make the game work. It should compare the bullet position against the chamber position. - -## 💡 Hints: - -+ If the bullet position `firePosition` matches the chamber position given by the function `spinChamber`, the function `fireGun()` should return `You're dead!`. - -+ If the bullet position `firePosition` doesn't match the chamber position given by the function `spinChamber`, the function `fireGun()` should return `Keep playing!`. - -+ The function `spinChamber` returns a random number between 1 and 6. diff --git a/exercises/21-Russian_Roulette/app.js b/exercises/21-Russian_Roulette/app.js deleted file mode 100644 index b775e5ff..00000000 --- a/exercises/21-Russian_Roulette/app.js +++ /dev/null @@ -1,16 +0,0 @@ -// firePosition will be the position in which the gun will fire. -let firePosition = 1; - -// The output of spinChamber will be a number and it can be passed as a parameter to the fireGun function. -const spinChamber = () => { - let chamberPosition = Math.floor((Math.random() * 6) + 1); - return chamberPosition; -}; - -// Remove the // below and complete the commented lines -const fireGun = (bulletPosition) => { - // if (... === firePosition) return ("You're dead!"); - // else return ("Keep playing!"); -}; - -console.log(fireGun(spinChamber())); diff --git a/exercises/21-Russian_Roulette/solution.hide.js b/exercises/21-Russian_Roulette/solution.hide.js deleted file mode 100644 index fe5682db..00000000 --- a/exercises/21-Russian_Roulette/solution.hide.js +++ /dev/null @@ -1,18 +0,0 @@ -// firePosition will be the position in which the gun will fire. -let firePosition = 1; - -// The output of spinChamber will be a number and it can be passed as a parameter to the fireGun function. -const spinChamber = () => { - let chamberPosition = Math.floor((Math.random() * 6) + 1); - return chamberPosition; -}; - -// Remove the // below and complete the commented lines -const fireGun = (bulletPosition) => { - if (bulletPosition === firePosition) { - return ("You're dead!"); - } - else return ("Keep playing!"); -}; - -console.log(fireGun(spinChamber())); diff --git a/exercises/21-Russian_Roulette/tests.js b/exercises/21-Russian_Roulette/tests.js deleted file mode 100644 index 59881ac2..00000000 --- a/exercises/21-Russian_Roulette/tests.js +++ /dev/null @@ -1,39 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const rewire = require('rewire'); - -jest.dontMock('fs'); -let _buffer = ""; -let _log = console.log; -const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); -global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); - - -describe('All the javascript should match', function () { - // jest.resetModules(); - - const app = rewire("./app"); - const fireGun = app.__get__("fireGun"); - const firePosition = app.__get__("firePosition"); - - test('The function "fireGun" should exist', () => { - const file = rewire("./app.js"); - const sum = file.__get__("fireGun"); - expect(sum).not.toBe(undefined); - }) - it('Use "if" conditional;', function () { - const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); - expect(app_content).toMatch(/if(\s*)\(/); - }); - - it('If fireGun() is false, message should be "Keep playing!"', function () { - for (let i = 1; i <= 6; i++) { - if (i === firePosition) { - expect(fireGun(i)).toContain("You're dead!"); - } - else { - expect(fireGun(i)).toContain("Keep playing!"); - } - } - }); -}); diff --git a/exercises/21-Your_first_array/README.es.md b/exercises/21-Your_first_array/README.es.md new file mode 100644 index 00000000..9b41a360 --- /dev/null +++ b/exercises/21-Your_first_array/README.es.md @@ -0,0 +1,46 @@ +--- +tutorial: "https://www.youtube.com/watch?v=prIqHDmw5r0" +--- + +# `21` Tu Primer Array + +Un array es una lista de valores. Los arrays son una de las estructuras de datos más importantes en programación porque nos permiten almacenar múltiples valores en una sola variable. + +Los arrays se declaran con corchetes `[]` y pueden contener cualquier tipo de dato: + +```js +let fruits = ["manzana", "plátano", "naranja"]; +let numeros = [1, 2, 3, 4, 5]; +let mixto = [1, "hola", true, 3.14]; +``` + +Puedes acceder a cada elemento en un array usando su **índice** (posición). Recuerda que los índices comienzan en `0`: + +```js +let fruits = ["manzana", "plátano", "naranja"]; +console.log(fruits[0]); // "manzana" +console.log(fruits[1]); // "plátano" +console.log(fruits[2]); // "naranja" +``` + +## 📝 Instrucciones: + +1. Crea un array llamado `colors` con al menos 3 nombres de colores como strings. +2. Usa `console.log()` para imprimir cada color accediendo por su posición de índice. +3. Imprime el array completo en la consola. + +## Ejemplo: + +```js +let animals = ["perro", "gato", "pájaro"]; +console.log(animals[0]); // "perro" +console.log(animals[1]); // "gato" +console.log(animals[2]); // "pájaro" +console.log(animals); // ["perro", "gato", "pájaro"] +``` + +## 💡 Pista: + ++ Recuerda: los índices de arrays comienzan en 0, ¡no en 1! ++ Puedes almacenar cualquier tipo de dato dentro de un array. + diff --git a/exercises/21-Your_first_array/README.md b/exercises/21-Your_first_array/README.md new file mode 100644 index 00000000..3b80a230 --- /dev/null +++ b/exercises/21-Your_first_array/README.md @@ -0,0 +1,46 @@ +--- +tutorial: "https://www.youtube.com/watch?v=prIqHDmw5r0" +--- + +# `21` Your First Array + +An array is a list of values. Arrays are one of the most important data structures in programming because they allow us to store multiple values in a single variable. + +Arrays are declared with square brackets `[]` and can hold any type of data: + +```js +let fruits = ["apple", "banana", "orange"]; +let numbers = [1, 2, 3, 4, 5]; +let mixed = [1, "hello", true, 3.14]; +``` + +You can access each element in an array using its **index** (position). Remember that indices start at `0`: + +```js +let fruits = ["apple", "banana", "orange"]; +console.log(fruits[0]); // "apple" +console.log(fruits[1]); // "banana" +console.log(fruits[2]); // "orange" +``` + +## 📝 Instructions: + +1. Create an array called `colors` with at least 3 color names as strings. +2. Use `console.log()` to print each color accessing it by its index position. +3. Print the array itself to the console. + +## Example: + +```js +let animals = ["dog", "cat", "bird"]; +console.log(animals[0]); // "dog" +console.log(animals[1]); // "cat" +console.log(animals[2]); // "bird" +console.log(animals); // ["dog", "cat", "bird"] +``` + +## 💡 Hint: + ++ Remember: array indexes start at 0, not 1! ++ You can store any type of data inside an array. + diff --git a/exercises/21-Your_first_array/app.js b/exercises/21-Your_first_array/app.js new file mode 100644 index 00000000..2fa42293 --- /dev/null +++ b/exercises/21-Your_first_array/app.js @@ -0,0 +1,8 @@ +//Create an array with at least 3 colors +let colors = []; + +//access and print each color by its index + +//print the array +//your code here + diff --git a/exercises/21-Your_first_array/solution.hide.js b/exercises/21-Your_first_array/solution.hide.js new file mode 100644 index 00000000..d7f21ffa --- /dev/null +++ b/exercises/21-Your_first_array/solution.hide.js @@ -0,0 +1,10 @@ +//Create an array with at least 3 colors +let colors = ["red", "blue", "green"]; + +//access and print each color by its index +console.log(colors[0]); +console.log(colors[1]); +console.log(colors[2]); + +//print the array +console.log(colors); diff --git a/exercises/21-Your_first_array/tests.js b/exercises/21-Your_first_array/tests.js new file mode 100644 index 00000000..2a266f3a --- /dev/null +++ b/exercises/21-Your_first_array/tests.js @@ -0,0 +1,32 @@ + +const fs = require('fs'); +const path = require('path'); + +jest.dontMock('fs'); +let _buffer = ""; +let _log = console.log; + +global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); + +describe('Array exercise', function () { + afterEach(() => { jest.resetModules(); }); + + it('Should have an array called "colors"', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+colors\s*=\s*\[/); + }); + + it('Should print at least 3 elements from the colors array', function () { + _buffer = ""; + const { colors } = require('./app.js'); + const logs = _buffer.trim().split('\n'); + expect(logs.length).toBeGreaterThanOrEqual(3); + }); + + it('Should print the array itself', function () { + _buffer = ""; + require('./app.js'); + expect(_buffer).toMatch(/,/); // arrays have commas when printed + }); +}); diff --git a/exercises/22-Array_methods/README.es.md b/exercises/22-Array_methods/README.es.md new file mode 100644 index 00000000..2ba6cf8a --- /dev/null +++ b/exercises/22-Array_methods/README.es.md @@ -0,0 +1,49 @@ +--- +tutorial: "https://www.youtube.com/watch?v=prIqHDmw5r0" +--- + +# `22` Métodos de Arrays + +Los arrays tienen muchos métodos incorporados que nos permiten manipularlos. Los más comunes son: + +- **`push()`**: Añade uno o más elementos al final del array +- **`pop()`**: Elimina el último elemento del array +- **`shift()`**: Elimina el primer elemento del array +- **`unshift()`**: Añade uno o más elementos al principio del array +- **`length`**: Propiedad que devuelve el número de elementos en un array + +```js +let fruits = ["manzana", "plátano"]; +fruits.push("naranja"); // fruits es ahora ["manzana", "plátano", "naranja"] +console.log(fruits.length); // 3 + +let lastFruit = fruits.pop(); // elimina "naranja", lastFruit = "naranja" +console.log(fruits); // ["manzana", "plátano"] + +fruits.unshift("uva"); // fruits es ahora ["uva", "manzana", "plátano"] +let firstFruit = fruits.shift(); // elimina "uva", firstFruit = "uva" +``` + +## 📝 Instrucciones: + +1. Crea un array llamado `students` con 3 nombres de estudiantes. +2. Añade un nuevo nombre de estudiante al final usando `push()`. +3. Elimina el primer estudiante usando `shift()`. +4. Imprime la longitud del array. +5. Imprime el array final. + +## Ejemplo: + +```js +let team = ["Alice", "Bob"]; +team.push("Charlie"); // ["Alice", "Bob", "Charlie"] +team.shift(); // ["Bob", "Charlie"] +console.log(team.length); // 2 +console.log(team); // ["Bob", "Charlie"] +``` + +## 💡 Pista: + ++ Los métodos son funciones que pertenecen a objetos. ¡Los arrays también son objetos! ++ `push()` y `unshift()` añaden elementos, mientras que `pop()` y `shift()` los eliminan. + diff --git a/exercises/22-Array_methods/README.md b/exercises/22-Array_methods/README.md new file mode 100644 index 00000000..2fe5f768 --- /dev/null +++ b/exercises/22-Array_methods/README.md @@ -0,0 +1,49 @@ +--- +tutorial: "https://www.youtube.com/watch?v=prIqHDmw5r0" +--- + +# `22` Array Methods + +Arrays have many built-in methods that allow us to manipulate them. The most common ones are: + +- **`push()`**: Adds one or more elements to the end of an array +- **`pop()`**: Removes the last element from an array +- **`shift()`**: Removes the first element from an array +- **`unshift()`**: Adds one or more elements to the beginning of an array +- **`length`**: Property that returns the number of elements in an array + +```js +let fruits = ["apple", "banana"]; +fruits.push("orange"); // fruits is now ["apple", "banana", "orange"] +console.log(fruits.length); // 3 + +let lastFruit = fruits.pop(); // removes "orange", lastFruit = "orange" +console.log(fruits); // ["apple", "banana"] + +fruits.unshift("grape"); // fruits is now ["grape", "apple", "banana"] +let firstFruit = fruits.shift(); // removes "grape", firstFruit = "grape" +``` + +## 📝 Instructions: + +1. Create an array called `students` with 3 student names. +2. Add a new student name to the end using `push()`. +3. Remove the first student using `shift()`. +4. Print the length of the array. +5. Print the final array. + +## Example: + +```js +let team = ["Alice", "Bob"]; +team.push("Charlie"); // ["Alice", "Bob", "Charlie"] +team.shift(); // ["Bob", "Charlie"] +console.log(team.length); // 2 +console.log(team); // ["Bob", "Charlie"] +``` + +## 💡 Hint: + ++ Methods are functions that belong to objects. Arrays are objects too! ++ `push()` and `unshift()` add elements, while `pop()` and `shift()` remove them. + diff --git a/exercises/22-Array_methods/app.js b/exercises/22-Array_methods/app.js new file mode 100644 index 00000000..523c83a6 --- /dev/null +++ b/exercises/22-Array_methods/app.js @@ -0,0 +1,14 @@ +//Create an array called students with 3 names +let students = []; + +//Add a new student name to the end using push() +//your code here + +//Remove the first student using shift() +//your code here + +//Print the length of the array +//your code here + +//Print the final array +//your code here diff --git a/exercises/22-Array_methods/solution.hide.js b/exercises/22-Array_methods/solution.hide.js new file mode 100644 index 00000000..d1930e7f --- /dev/null +++ b/exercises/22-Array_methods/solution.hide.js @@ -0,0 +1,14 @@ +//Create an array called students with 3 names +let students = ["Maria", "Juan", "Pedro"]; + +//Add a new student name to the end using push() +students.push("Ana"); + +//Remove the first student using shift() +students.shift(); + +//Print the length of the array +console.log(students.length); + +//Print the final array +console.log(students); diff --git a/exercises/22-Array_methods/tests.js b/exercises/22-Array_methods/tests.js new file mode 100644 index 00000000..256e1235 --- /dev/null +++ b/exercises/22-Array_methods/tests.js @@ -0,0 +1,37 @@ + +const fs = require('fs'); +const path = require('path'); + +jest.dontMock('fs'); +let _buffer = ""; + +global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); + +describe('Array methods exercise', function () { + afterEach(() => { jest.resetModules(); }); + + it('Should have an array called "students"', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+students\s*=/); + }); + + it('Should use push() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.push\(/); + }); + + it('Should use shift() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.shift\(/); + }); + + it('Should print the array length and final array', function () { + _buffer = ""; + require('./app.js'); + const logs = _buffer.trim().split('\n'); + expect(logs.length).toBeGreaterThanOrEqual(2); + }); +}); diff --git a/exercises/22-The_Beatles/README.es.md b/exercises/22-The_Beatles/README.es.md deleted file mode 100644 index ce6d9bfc..00000000 --- a/exercises/22-The_Beatles/README.es.md +++ /dev/null @@ -1,27 +0,0 @@ -# `022` The Beatles - -¿A quién no le gustan Los Beatles? Un estudio de la BBC ha mostrado que el 90% de los niños de ahora no conocen la banda... Qué triste... 😟 - -Abajo está el coro de una de las canciones más famosas de Los Beatles, *Let it be*: - -> Let it be, let it be, let it be, let it be - -> Whisper words of wisdom - -> Let it be - -## 📝 Instrucciones: - -1. Crea una función llamada `sing()` que devuelva un string con la letra exacta que puedes oír desde el minuto 3:20 hasta el final de la canción a los 3:50 minutos. - -## 💻 Resultado esperado: - -```js -"let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be" -``` - -## 💡 Pistas: - -+ Las palabras `let it be` se repiten todo el tiempo, probablemente debas crear un bucle (loop) para eso. - -+ Aquí está la canción: https://www.youtube.com/watch?v=QDYfEBY9NM4 diff --git a/exercises/22-The_Beatles/README.md b/exercises/22-The_Beatles/README.md deleted file mode 100644 index 2b4c7226..00000000 --- a/exercises/22-The_Beatles/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# `22` The Beatles - -Who doesn't like The Beatles? A BBC study reported that 90% of kids today don't know the band. Heartbreaking... 😟 - -Below is the chorus of one of the most famous Beatles songs, *Let It Be*: - -> Let it be, let it be, let it be, let it be - -> Whisper words of wisdom - -> Let it be - -## 📝 Instructions: - -1. Create a function called `sing()` that returns a string with the exact same lyrics which you can hear from the 3:20 mark to the end of the song at 3:50. - -## 💻 Expected output: - -```js -"let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be" -``` - -## 💡 Hints: - -+ The words `let it be` are repeated in the string. Creating a loop would be a good idea. - -+ Here is the song: https://www.youtube.com/watch?v=QDYfEBY9NM4 diff --git a/exercises/22-The_Beatles/app.js b/exercises/22-The_Beatles/app.js deleted file mode 100644 index 1111c793..00000000 --- a/exercises/22-The_Beatles/app.js +++ /dev/null @@ -1,5 +0,0 @@ - - -//Your code above ^^^ - -console.log(sing()); \ No newline at end of file diff --git a/exercises/22-The_Beatles/solution.hide.js b/exercises/22-The_Beatles/solution.hide.js deleted file mode 100644 index 1136e9f1..00000000 --- a/exercises/22-The_Beatles/solution.hide.js +++ /dev/null @@ -1,13 +0,0 @@ -function sing(){ - let str = ""; - for(let i = 0; i < 11; i++){ - if(i === 4) str += 'there will be an answer, '; - else if (i === 10) str += 'whisper words of wisdom, let it be'; - else str += 'let it be, '; - } - return str; -} - -//Your code above ^^^ - -console.log(sing()); diff --git a/exercises/22-The_Beatles/tests.js b/exercises/22-The_Beatles/tests.js deleted file mode 100644 index 2386c41e..00000000 --- a/exercises/22-The_Beatles/tests.js +++ /dev/null @@ -1,47 +0,0 @@ - -const fs = require('fs'); -const path = require('path'); -const rewire = require('rewire'); - -jest.dontMock('fs'); -//here we are going to store and accumulate (concatenate) all the console log's from the exercise -let _buffer = ""; -let _log = console.log; - -// let's override the console.log function to mock it, -// but we are also going to save what is supposed to be the output of the console inside _buffer -global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); - -it('Use a for loop', function () { - const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); - expect(app_content).toMatch(/for(\s*)\(/); -}); - -test("Function sing should exist", function () { - const file = rewire("./app.js"); - const sing = file.__get__('sing'); - expect(sing).toBeTruthy(); -}); - -test("Function sing should return the exact lyrics of the song", function () { - const file = rewire("./app.js"); - const sing = file.__get__('sing'); - expect(sing()).toBe('let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be'); -}); - - -describe('All the javascript should match', function () { - beforeEach(() => { - //here I import the HTML into the document - }); - afterEach(() => { jest.resetModules(); }); - - it('console.log() function should be called with proper lyrics order', function () { - - const file = require("./app.js"); - - expect(console.log).toHaveBeenCalledWith("let it be, let it be, let it be, let it be, there will be an answer, let it be, let it be, let it be, let it be, let it be, whisper words of wisdom, let it be"); - - expect(console.log.mock.calls.length).toBe(1); - }); -}); diff --git a/exercises/23-Bottles_of_milk/README.es.md b/exercises/23-Bottles_of_milk/README.es.md deleted file mode 100644 index 02c2bfba..00000000 --- a/exercises/23-Bottles_of_milk/README.es.md +++ /dev/null @@ -1,29 +0,0 @@ -# `23` Bottles of Milk - -¿Has escuchado la canción sobre 99 botellas de leche (99 bottles of milk)? Es una gran canción - para nada aburrida...😆 - -Aquí la puedes escuchar: https://www.youtube.com/watch?v=Xy-da43E6Lo - -## 📝 Instrucciones: - -1. Escribe un algoritmo para imprimir la misma letra. Debes usar un `for` loop. - -## 💻 Resultado esperado: - -```js -`99 bottles of milk on the wall, 99 bottles of milk. Take one down and pass it around, 98 bottles of milk on the wall.` - -`98 bottles of milk on the wall, 98 bottles of milk. Take one down and pass it around, 97 bottles of milk on the wall.` - -... - -`1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.` - -`No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.` -``` - -## 💡 Pistas: - -+ Al final de la canción, la letra cambia porque es sólo una botella (singular en vez de plural). - -+ Lee la última parte de la letra y verás como la última línea cambia a `Go to the store and buy some more` (anda a comprar más leche). diff --git a/exercises/23-Bottles_of_milk/README.md b/exercises/23-Bottles_of_milk/README.md deleted file mode 100644 index 3556a308..00000000 --- a/exercises/23-Bottles_of_milk/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# `23` Bottles of Milk - -Have you heard the song about 99 bottles of milk? It is a great song - not boring at all... 😆 - -Here you can hear it: https://www.youtube.com/watch?v=Xy-da43E6Lo - -## 📝 Instructions: - -1. Write an algorithm to print the exact same lyrics. You must use a `for` loop. - -## 💻 Expected output: - -```js -`99 bottles of milk on the wall, 99 bottles of milk. Take one down and pass it around, 98 bottles of milk on the wall.` - -`98 bottles of milk on the wall, 98 bottles of milk. Take one down and pass it around, 97 bottles of milk on the wall.` - -... - -`1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall.` - -`No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall.` -``` - -## 💡 Hint: - -+ The lyrics change slightly when there is one bottle left (singular instead of plural). - -+ When there are no more bottles, the last verse changes to `Go to the store and buy some more`. - - diff --git a/exercises/23-Bottles_of_milk/app.js b/exercises/23-Bottles_of_milk/app.js deleted file mode 100644 index f37016c1..00000000 --- a/exercises/23-Bottles_of_milk/app.js +++ /dev/null @@ -1 +0,0 @@ -// Your code here: diff --git a/exercises/23-Bottles_of_milk/solution.hide.js b/exercises/23-Bottles_of_milk/solution.hide.js deleted file mode 100644 index b55be010..00000000 --- a/exercises/23-Bottles_of_milk/solution.hide.js +++ /dev/null @@ -1,15 +0,0 @@ -function song(){ - for (let i = 99; i >= 0; i--) { - if (i == 1) { - console.log("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall."); - } else if (i == 0) { - console.log("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall."); - } else if (i== 2) { - console.log(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottle of milk on the wall.`); - } else { - console.log(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottles of milk on the wall.`); - } - } -} - -song() \ No newline at end of file diff --git a/exercises/23-Bottles_of_milk/tests.js b/exercises/23-Bottles_of_milk/tests.js deleted file mode 100644 index 18f44634..00000000 --- a/exercises/23-Bottles_of_milk/tests.js +++ /dev/null @@ -1,52 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const js = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); - -jest.dontMock('fs'); -//here we are going to store and accumulate (concatenate) all the console log's from the exercise -let _buffer = ""; -let _log = console.log; - -// let's override the console.log function to mock it, -// but we are also going to save what is supposed to be the output of the console inside _buffer -global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); - -describe('All the javascript should match', function () { - it('console.log() function should be called 99 or 100 times (depending on your approach)', function () { - const file = require("./app.js"); - expect([100,99].includes(console.log.mock.calls.length)).toBeTruthy(); - }); - - it('Use a for loop', function () { - const app_content = fs.readFileSync(path.resolve(__dirname, './app.js'), 'utf8'); - expect(app_content).toMatch(/for(\s*)\(/); - }); - - it('console.log() function should be called with proper lyrics for more than one bottle', function () { - const file = require("./app.js"); - for(let i = 99; i > 2; i--){ - expect(_buffer).toContain(`${i} bottles of milk on the wall, ${i} bottles of milk. Take one down and pass it around, ${i-1} bottles of milk on the wall.`); - } - }); - - it('console.log() function should be called with proper lyrics for two bottles', function () { - const file = require("./app.js"); - expect(_buffer).toContain("2 bottles of milk on the wall, 2 bottles of milk. Take one down and pass it around, 1 bottle of milk on the wall."); - }); - - it('console.log() function should be called with proper lyrics for one bottle', function () { - const file = require("./app.js"); - expect(_buffer).toContain("1 bottle of milk on the wall, 1 bottle of milk. Take one down and pass it around, no more bottles of milk on the wall."); - }); - - it('console.log() function should be called with proper lyrics for 0 bottles', function () { - const file = require("./app.js"); - expect(_buffer).toContain("No more bottles of milk on the wall, no more bottles of milk. Go to the store and buy some more, 99 bottles of milk on the wall."); - }); - - it('You should use a for loop to print the lyrics of the song', function () { - const file = require("./app.js"); - let regex = /for\s*\(/gm - expect(regex.test(js.toString())).toBeTruthy(); - }); -}); diff --git a/exercises/23-Your_first_object/README.es.md b/exercises/23-Your_first_object/README.es.md new file mode 100644 index 00000000..08b01375 --- /dev/null +++ b/exercises/23-Your_first_object/README.es.md @@ -0,0 +1,62 @@ +--- +tutorial: "https://www.youtube.com/watch?v=X0ujO1vQ5RE" +--- + +# `23` Tu Primer Objeto + +Un objeto es una forma de almacenar datos y funcionalidad relacionados juntos. Los objetos se crean usando llaves `{}` y contienen **pares clave-valor**. + +```js +let person = { + name: "Juan", + age: 25, + city: "Madrid", + isStudent: true +}; +``` + +Puedes acceder a las propiedades del objeto usando **notación de punto** o **notación de corchetes**: + +```js +let person = { + name: "Juan", + age: 25 +}; + +console.log(person.name); // "Juan" (notación de punto) +console.log(person["age"]); // 25 (notación de corchetes) + +person.city = "Madrid"; // añadir una nueva propiedad +console.log(person); // {name: "Juan", age: 25, city: "Madrid"} +``` + +## 📝 Instrucciones: + +1. Crea un objeto llamado `user` con al menos 3 propiedades (p.ej., name, age, email). +2. Accede e imprime cada propiedad usando notación de punto. +3. Añade una nueva propiedad al objeto. +4. Imprime el objeto completo. + +## Ejemplo: + +```js +let car = { + brand: "Toyota", + model: "Camry", + year: 2020 +}; + +console.log(car.brand); // "Toyota" +console.log(car.model); // "Camry" +console.log(car.year); // 2020 + +car.color = "azul"; +console.log(car); // {brand: "Toyota", model: "Camry", year: 2020, color: "azul"} +``` + +## 💡 Pista: + ++ Los objetos ayudan a organizar datos relacionados juntos. ++ Las propiedades se separan por comas. ++ ¡Puedes añadir nuevas propiedades en cualquier momento! + diff --git a/exercises/23-Your_first_object/README.md b/exercises/23-Your_first_object/README.md new file mode 100644 index 00000000..5b2bc85d --- /dev/null +++ b/exercises/23-Your_first_object/README.md @@ -0,0 +1,62 @@ +--- +tutorial: "https://www.youtube.com/watch?v=X0ujO1vQ5RE" +--- + +# `23` Your First Object + +An object is a way to store related data and functionality together. Objects are created using curly braces `{}` and contain **key-value pairs**. + +```js +let person = { + name: "John", + age: 25, + city: "New York", + isStudent: true +}; +``` + +You can access object properties using **dot notation** or **bracket notation**: + +```js +let person = { + name: "John", + age: 25 +}; + +console.log(person.name); // "John" (dot notation) +console.log(person["age"]); // 25 (bracket notation) + +person.city = "New York"; // add a new property +console.log(person); // {name: "John", age: 25, city: "New York"} +``` + +## 📝 Instructions: + +1. Create an object called `user` with at least 3 properties (e.g., name, age, email). +2. Access and print each property using dot notation. +3. Add a new property to the object. +4. Print the complete object. + +## Example: + +```js +let car = { + brand: "Toyota", + model: "Camry", + year: 2020 +}; + +console.log(car.brand); // "Toyota" +console.log(car.model); // "Camry" +console.log(car.year); // 2020 + +car.color = "blue"; +console.log(car); // {brand: "Toyota", model: "Camry", year: 2020, color: "blue"} +``` + +## 💡 Hint: + ++ Objects help organize related data together. ++ Properties are separated by commas. ++ You can add new properties at any time! + diff --git a/exercises/23-Your_first_object/app.js b/exercises/23-Your_first_object/app.js new file mode 100644 index 00000000..8f6cc4f8 --- /dev/null +++ b/exercises/23-Your_first_object/app.js @@ -0,0 +1,11 @@ +//Create an object called user with at least 3 properties +let user = {}; + +//Access and print each property using dot notation +//your code here + +//Add a new property to the object +//your code here + +//Print the complete object +//your code here diff --git a/exercises/23-Your_first_object/solution.hide.js b/exercises/23-Your_first_object/solution.hide.js new file mode 100644 index 00000000..2f12439c --- /dev/null +++ b/exercises/23-Your_first_object/solution.hide.js @@ -0,0 +1,17 @@ +//Create an object called user with at least 3 properties +let user = { + name: "Carlos", + age: 30, + email: "carlos@example.com" +}; + +//Access and print each property using dot notation +console.log(user.name); +console.log(user.age); +console.log(user.email); + +//Add a new property to the object +user.city = "Barcelona"; + +//Print the complete object +console.log(user); diff --git a/exercises/23-Your_first_object/tests.js b/exercises/23-Your_first_object/tests.js new file mode 100644 index 00000000..066d1d82 --- /dev/null +++ b/exercises/23-Your_first_object/tests.js @@ -0,0 +1,37 @@ + +const fs = require('fs'); +const path = require('path'); + +jest.dontMock('fs'); +let _buffer = ""; + +global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); + +describe('Object exercise', function () { + afterEach(() => { jest.resetModules(); }); + + it('Should have an object called "user"', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+user\s*=/); + }); + + it('Should have at least 3 properties in the user object', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/:\s*\w+/g); + }); + + it('Should access properties using dot notation', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/user\.\w+/); + }); + + it('Should print the user object and its properties', function () { + _buffer = ""; + require('./app.js'); + const logs = _buffer.trim().split('\n'); + expect(logs.length).toBeGreaterThanOrEqual(4); + }); +}); diff --git a/exercises/24-For_of_loop/README.es.md b/exercises/24-For_of_loop/README.es.md new file mode 100644 index 00000000..145387f6 --- /dev/null +++ b/exercises/24-For_of_loop/README.es.md @@ -0,0 +1,62 @@ +--- +tutorial: "https://www.youtube.com/watch?v=Y0LSuCI3Xv8" +--- + +# `24` Bucle For...of + +El bucle `for...of` es una forma más limpia de iterar a través de los elementos de un array. A diferencia del bucle `for` tradicional que usa un índice, `for...of` te da acceso directo a cada elemento. + +```js +let fruits = ["manzana", "plátano", "naranja"]; + +// Bucle for tradicional +for (let i = 0; i < fruits.length; i++) { + console.log(fruits[i]); +} + +// Bucle for...of (¡más fácil!) +for (let fruit of fruits) { + console.log(fruit); +} +``` + +Ambos producen el mismo resultado, pero `for...of` es más legible y simple cuando no necesitas el índice. + +Puedes usar `for...of` con: +- Arrays +- Strings (itera a través de cada carácter) +- Cualquier objeto iterable + +```js +let word = "Hola"; +for (let letter of word) { + console.log(letter); // H, o, l, a +} +``` + +## 📝 Instrucciones: + +1. Crea un array llamado `numbers` con al menos 5 números. +2. Usa un bucle `for...of` para iterar a través del array. +3. Dentro del bucle, imprime cada número multiplicado por 2. +4. También crea un string e usa `for...of` para imprimir cada carácter. + +## Ejemplo: + +```js +let animals = ["gato", "perro", "pájaro"]; +for (let animal of animals) { + console.log(animal.toUpperCase()); +} + +let name = "Carlos"; +for (let char of name) { + console.log(char); +} +``` + +## 💡 Pista: + ++ `for...of` es perfecto cuando necesitas acceder a los valores, no al índice. ++ `for...of` funciona con cualquier iterable (arrays, strings, etc.). + diff --git a/exercises/24-For_of_loop/README.md b/exercises/24-For_of_loop/README.md new file mode 100644 index 00000000..afb66fc4 --- /dev/null +++ b/exercises/24-For_of_loop/README.md @@ -0,0 +1,62 @@ +--- +tutorial: "https://www.youtube.com/watch?v=Y0LSuCI3Xv8" +--- + +# `24` For...of Loop + +The `for...of` loop is a cleaner way to iterate through the elements of an array. Unlike the traditional `for` loop that uses an index, `for...of` gives you direct access to each element. + +```js +let fruits = ["apple", "banana", "orange"]; + +// Traditional for loop +for (let i = 0; i < fruits.length; i++) { + console.log(fruits[i]); +} + +// for...of loop (easier!) +for (let fruit of fruits) { + console.log(fruit); +} +``` + +Both produce the same output, but `for...of` is more readable and simpler when you don't need the index. + +You can use `for...of` with: +- Arrays +- Strings (iterates through each character) +- Any iterable object + +```js +let word = "Hello"; +for (let letter of word) { + console.log(letter); // H, e, l, l, o +} +``` + +## 📝 Instructions: + +1. Create an array called `numbers` with at least 5 numbers. +2. Use a `for...of` loop to iterate through the array. +3. Inside the loop, print each number multiplied by 2. +4. Also create a string and use `for...of` to print each character. + +## Example: + +```js +let animals = ["cat", "dog", "bird"]; +for (let animal of animals) { + console.log(animal.toUpperCase()); +} + +let name = "Alice"; +for (let char of name) { + console.log(char); +} +``` + +## 💡 Hint: + ++ `for...of` is perfect when you need to access the values, not the index. ++ `for...of` works with any iterable (arrays, strings, etc.). + diff --git a/exercises/24-For_of_loop/app.js b/exercises/24-For_of_loop/app.js new file mode 100644 index 00000000..7685bded --- /dev/null +++ b/exercises/24-For_of_loop/app.js @@ -0,0 +1,10 @@ +//Create an array called numbers with at least 5 numbers +let numbers = []; + +//Use a for...of loop to iterate through the array +//Inside the loop, print each number multiplied by 2 +//your code here + +//Create a string and use for...of to print each character +let word = ""; +//your code here \ No newline at end of file diff --git a/exercises/24-For_of_loop/solution.hide.js b/exercises/24-For_of_loop/solution.hide.js new file mode 100644 index 00000000..b947dc94 --- /dev/null +++ b/exercises/24-For_of_loop/solution.hide.js @@ -0,0 +1,14 @@ +//Create an array called numbers with at least 5 numbers +let numbers = [1, 2, 3, 4, 5]; + +//Use a for...of loop to iterate through the array +//Inside the loop, print each number multiplied by 2 +for (let num of numbers) { + console.log(num * 2); +} + +//Create a string and use for...of to print each character +let word = "Hello"; +for (let char of word) { + console.log(char); +} diff --git a/exercises/24-For_of_loop/tests.js b/exercises/24-For_of_loop/tests.js new file mode 100644 index 00000000..2e2b5c87 --- /dev/null +++ b/exercises/24-For_of_loop/tests.js @@ -0,0 +1,37 @@ + +const fs = require('fs'); +const path = require('path'); + +jest.dontMock('fs'); +let _buffer = ""; + +global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); + +describe('For...of loop exercise', function () { + afterEach(() => { jest.resetModules(); }); + + it('Should have an array called "numbers"', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+numbers\s*=/); + }); + + it('Should use for...of loop', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/for\s*\(\s*let\s+\w+\s+of\s+/); + }); + + it('Should iterate through numbers and print them multiplied by 2', function () { + _buffer = ""; + require('./app.js'); + const logs = _buffer.trim().split('\n'); + expect(logs.length).toBeGreaterThanOrEqual(5); + }); + + it('Should also iterate through a string', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+word\s*=\s*"/); + }); +}); diff --git a/exercises/24-Javascript_Objects/README.es.md b/exercises/24-Javascript_Objects/README.es.md deleted file mode 100644 index 9a4022ff..00000000 --- a/exercises/24-Javascript_Objects/README.es.md +++ /dev/null @@ -1,106 +0,0 @@ -# `24` JavaScript Objects - -A menudo te encontrarás queriendo guardar más información en menos espacio, especialmente si está toda relacionada. - -Por ejemplo, digamos que queremos representar autos dentro de variables: - -```js -let car1Model = "Corolla"; -let car1Make = "Toyota"; -let car1Color = "green"; -let car1Year = 2015; - -let car2Model = "Santa Fe"; -let car2Make = "Hyundai"; -let car2Color = "purple"; -let car2Year = 2013; - -//... (¿entiendes la idea?) -``` - - -Hay un enfoque óptimo para esto, son los **objetos**. Los **objetos (objects)** son un tipo de variable que contienen información (otras variables) en forma de `key:value`. - -Entonces, si queremos traducir (y optimizar) las variables desde car (auto) a un Object, hacemos: - -```js -const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015}; -``` - -Puedes ver el `key:value` separado por una coma. - -Y para que nosotros (los desarrolladores) podamos leerlas más fácilmente las escribimos así: - -```js -const car1 = { - model: "Corolla", - make: "Toyota", - color: "green", - year: 2015 -}; -``` - -Parece una función, ¿verdad? Pero no lo es. - -Ahora estamos guardando información de una forma más organizada, y si queremos obtener esa información podemos hacer: - -```js -console.log(car1.model); //imprime el modelo de car1 en la consola -``` - -Podemos tener todos los tipos de variables conocidas en JavaScript como valor(`value`) de cualquier `key` (¡incluyendo objetos!). Ahora imagina las posibilidades... - -```js -var person = { - name: "John", //String - lastName: "Doe", - age: 35, //Número - gender: "male", - luckyNumbers: [7, 11, 13, 17], //Array - significantOther: person2 //Objeto, sí, la misma variable/objeto definida después -}; - -var person2 = { - name: "Jane", - lastName: "Doe", - age: 38, - gender: "female", - luckyNumbers: [2, 4, 6, 8], - significantOther: person -}; - -var family = { - lastName: "Doe", - members: [person, person2] //Array de objetos -}; -``` - -Entonces, si en este escenario queremos saber el nombre del primer miembro de la familia Doe, decimos: - -```js -console.log(family.members[0].name); -``` - -O el 3er número de la suerte del `significantOther` del segundo miembro de la familia Doe: - -```js -console.log(family.members[1].significantOther.luckyNumbers[2]); -``` - -Cosas sencillas :) - -## 📝 Instrucciones: - -1. De forma automatizada, cambia el cuarto número de la suerte de John Doe (`luckyNumber`) a `33` (usa un comando, no cambies manualmente el código). - -2. De forma automatizada, crea una nueva persona y añádela al objeto familia. `Jimmy Doe`, `13`, `male`(masculino), `luckyNumbers` (números de la suerte): `1`, `2`, `3`, `4`; `significantOther: null`. - -3. Ahora por favor imprime (`console.log()`) la SUMA de todos los números de la suerte (`luckyNumbers`) de la familia Doe. - -## 💡 Pistas: - -+ Puedes obtener cada array de números de la suerte (`luckyNumbers`) desde el objeto de cada persona dentro del objeto familia. - -+ Una vez obtengas cada array, solo has un loop sobre él sumando cada elemento (como hemos hecho hasta ahora). Luego obtén el total de la suma de los 3 miembros de la familia. - -+ `null` también es un objeto. diff --git a/exercises/24-Javascript_Objects/README.md b/exercises/24-Javascript_Objects/README.md deleted file mode 100644 index d51b2d80..00000000 --- a/exercises/24-Javascript_Objects/README.md +++ /dev/null @@ -1,103 +0,0 @@ -# `24` JavaScript Objects - -Often you'll find yourself wanting to save more information in less space, especially if it's all related. - -For example, let's say that we want to represent cars into variables: - -```js -let car1Model = "Corolla"; -let car1Make = "Toyota"; -let car1Color = "green"; -let car1Year = 2015; - -let car2Model = "Santa Fe"; -let car2Make = "Hyundai"; -let car2Color = "purple"; -let car2Year = 2013; - -//... (you get the idea) -``` - -There's an optimized approach to this, it is called **Objects**. **Objects** are a type of variable that contains information (other variables) in a **key:value** manner. - -So if we want to translate (and optimize) the variables from the car into an Object, we do: - -```js -const car1 = {model: "Corolla", make: "Toyota", color: "green", year: 2015}; -``` - -You can see the `key:value` separated by a comma. And for us (developers) to read it easier we write it like this: - -```js -const car1 = { - model: "Corolla", - make: "Toyota", - color: "green", - year: 2015 -}; -``` - -Looks like a function, right? But it's not. - -Now we are storing information in a more organized way, and if we want to get that information we can do: - -```js -console.log(car1.model); //prints the model of car1 in the console -``` - -We can have all of the known types of variables defined as the value of any `key` (including objects!). Now imagine the possibilities... - -```js -var person = { - name: "John", //String - lastName: "Doe", - age: 35, //Number - gender: "male", - luckyNumbers: [7, 11, 13, 17], //Array - significantOther: person2 //Object, yes, the same variable/object defined after -}; - -var person2 = { - name: "Jane", - lastName: "Doe", - age: 38, - gender: "female", - luckyNumbers: [2, 4, 6, 8], - significantOther: person -}; - -var family = { - lastName: "Doe", - members: [person, person2] //Array of objects -}; -``` - -So, in this scenario if we want to know the name of the first member of the Doe family we do: - -```js -console.log(family.members[0].name); -``` - -Or the 3rd lucky number of the `significantOther` of the second member of the Doe family: - -```js -console.log(family.members[1].significantOther.luckyNumbers[2]); -``` - -Easy stuff :) - -## 📝 Instructions: - -1. Programmatically, change the fourth `luckyNumber` of John Doe to `33` (use a command, don't manually change the code). - -2. Programmatically, create a new person and add it to the family object. `Jimmy Doe`, `13`, `male`, `luckyNumbers`: `1`, `2`, `3`, `4`; `significantOther: null`. - -3. Now please print (`console.log()`) the SUM of all the `luckyNumbers` of the Doe family. - -## 💡 Hint: - -+ You can get each array of `luckyNumbers` from each person object inside the family object. - -+ Once you get each array, just loop over it adding every element (like we've been doing so far). And then add each sum of the 3 family members. - -+ `null` is also an object. diff --git a/exercises/24-Javascript_Objects/app.js b/exercises/24-Javascript_Objects/app.js deleted file mode 100644 index fa1e623a..00000000 --- a/exercises/24-Javascript_Objects/app.js +++ /dev/null @@ -1,38 +0,0 @@ -var person = { - name: "John", //String - lastName: "Doe", - age: 35, //Number - gender: "male", - luckyNumbers: [7, 11, 13, 17], //Array - significantOther: person2 //Object, yes, the same variable/object defined after -}; - -var person2 = { - name: "Jane", - lastName: "Doe", - age: 38, - gender: "female", - luckyNumbers: [2, 4, 6, 8], - significantOther: person -}; - -var family = { - lastName: "Doe", - members: [person, person2] //Array of objects, don't forget to add Jimmy -}; - - -function addAllFamilyLuckyNumbers(anArray){ - let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers. - - //To-Do: loop and add; consider nested loops - //Hint: use the anArray variable to get all of the lucky numbers - - return sumOfAllLuckyNumbers; -} - -//Enter all your code here: - - -//Do not make changes below: -console.log(addAllFamilyLuckyNumbers(family.members)); diff --git a/exercises/24-Javascript_Objects/solution.hide.js b/exercises/24-Javascript_Objects/solution.hide.js deleted file mode 100644 index 38a8923b..00000000 --- a/exercises/24-Javascript_Objects/solution.hide.js +++ /dev/null @@ -1,52 +0,0 @@ -var person = { - name: "John", //String - lastName: "Doe", - age: 35, //Number - gender: "male", - luckyNumbers: [7, 11, 13, 17], //Array - significantOther: person2 //Object, yes, the same variable/object defined after -}; - -var person2 = { - name: "Jane", - lastName: "Doe", - age: 38, - gender: "female", - luckyNumbers: [2, 4, 6, 8], - significantOther: person -}; - -var person3 = { - name: 'Jimmy', - lastName: 'Doe', - age: 13, - gender: "male", - luckyNumbers: [1, 2, 3, 4], - significantOther: null -} - -var family = { - lastName: "Doe", - members: [person, person2, person3] //Array of objects, don't forget to add Jimmy -}; - - -function addAllFamilyLuckyNumbers(anArray) { - let sumOfAllLuckyNumbers = 0; //sumOfAllLuckyNumbers is a number, the sum of all lucky numbers. - for (let i = 0; i < anArray.length; i++) { - for (let x = 0; x < anArray[i].luckyNumbers.length; x++) { - sumOfAllLuckyNumbers += anArray[i].luckyNumbers[x]; - } - } - //To-Do: loop and add; consider nested loops - //Hint: use the anArray variable to get all of the lucky numbers - - return sumOfAllLuckyNumbers; -} - -//Enter all your code here: -person.luckyNumbers[3] = 33; - - -//Do not make changes below: -console.log(addAllFamilyLuckyNumbers(family.members)); diff --git a/exercises/24-Javascript_Objects/tests.js b/exercises/24-Javascript_Objects/tests.js deleted file mode 100644 index 09952deb..00000000 --- a/exercises/24-Javascript_Objects/tests.js +++ /dev/null @@ -1,34 +0,0 @@ -const fs = require('fs'); -const path = require('path'); -const rewire = require('rewire'); - -jest.dontMock('fs'); -//here we are going to store and accumulate (concatenate) all the console log's from the exercise -let _buffer = ""; -let _log = console.log; - -// lets override the console.log function to mock it, -// but we are also going to save what supposed to be the ouput of the console inside _buffer -global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); - -const file = rewire("./app.js"); -const family = file.__get__("family"); - -describe('All the javascript should match', function () { - beforeEach(() => { - //here I import the HTML into the document - }); - afterEach(() => { jest.resetModules(); }); - - it("John Doe's fourth lucky number should be 33" , function(){ - expect(family.members[0].luckyNumbers[3]).toBe(33) - }) - - it('console.log() function should be called with 94 - sum of all family lucky numbers', function () { - const file = require("./app.js"); - expect(_buffer).toBe("94\n"); - //and I expect the console.log to be already called just one time. - expect(console.log.mock.calls.length).toBe(1); - - }); -}); diff --git a/exercises/25-String_methods/README.es.md b/exercises/25-String_methods/README.es.md new file mode 100644 index 00000000..74f37e4d --- /dev/null +++ b/exercises/25-String_methods/README.es.md @@ -0,0 +1,59 @@ +--- +tutorial: "https://www.youtube.com/watch?v=rRQnB3AYiF8" +--- + +# `25` Métodos de Strings + +Los strings tienen muchos métodos incorporados que nos permiten manipular y trabajar con texto. Aquí están los más comunes: + +- **`length`**: Devuelve el número de caracteres en un string +- **`toUpperCase()`**: Convierte el string a mayúsculas +- **`toLowerCase()`**: Convierte el string a minúsculas +- **`indexOf()`**: Devuelve la posición de la primera ocurrencia de un substring +- **`slice()`**: Extrae una parte de un string +- **`includes()`**: Comprueba si un string contiene un substring +- **`replace()`**: Reemplaza texto en un string +- **`trim()`**: Elimina espacios en blanco de ambos extremos + +```js +let message = "Hola Mundo"; + +console.log(message.length); // 10 +console.log(message.toUpperCase()); // "HOLA MUNDO" +console.log(message.toLowerCase()); // "hola mundo" +console.log(message.indexOf("Mundo")); // 5 +console.log(message.slice(0, 4)); // "Hola" +console.log(message.includes("Mundo")); // true +console.log(message.replace("Mundo", "JS")); // "Hola JS" +console.log(" espacios ".trim()); // "espacios" +``` + +## 📝 Instrucciones: + +1. Crea una variable de string con una oración. +2. Imprime la longitud del string. +3. Imprime el string en mayúsculas y minúsculas. +4. Usa `indexOf()` para encontrar la posición de una palabra. +5. Usa `slice()` para extraer parte del string. +6. Usa `includes()` para comprobar si una palabra existe en el string. +7. Usa `replace()` para reemplazar una palabra por otra. + +## Ejemplo: + +```js +let text = "JavaScript es increíble"; + +console.log(text.length); // 23 +console.log(text.toUpperCase()); // "JAVASCRIPT ES INCREÍBLE" +console.log(text.indexOf("increíble")); // 14 +console.log(text.slice(0, 10)); // "JavaScript" +console.log(text.includes("increíble")); // true +console.log(text.replace("increíble", "genial")); // "JavaScript es genial" +``` + +## 💡 Pista: + ++ Los strings son inmutables - los métodos devuelven nuevos strings, no modifican el original. ++ `indexOf()` devuelve -1 si el substring no se encuentra. ++ ¡Muchos métodos de string son sensibles a mayúsculas y minúsculas! + diff --git a/exercises/25-String_methods/README.md b/exercises/25-String_methods/README.md new file mode 100644 index 00000000..d2d0d089 --- /dev/null +++ b/exercises/25-String_methods/README.md @@ -0,0 +1,59 @@ +--- +tutorial: "https://www.youtube.com/watch?v=rRQnB3AYiF8" +--- + +# `25` String Methods + +Strings have many built-in methods that allow us to manipulate and work with text. Here are the most common ones: + +- **`length`**: Returns the number of characters in a string +- **`toUpperCase()`**: Converts the string to uppercase +- **`toLowerCase()`**: Converts the string to lowercase +- **`indexOf()`**: Returns the position of the first occurrence of a substring +- **`slice()`**: Extracts a part of a string +- **`includes()`**: Checks if a string contains a substring +- **`replace()`**: Replaces text in a string +- **`trim()`**: Removes whitespace from both ends + +```js +let message = "Hello World"; + +console.log(message.length); // 11 +console.log(message.toUpperCase()); // "HELLO WORLD" +console.log(message.toLowerCase()); // "hello world" +console.log(message.indexOf("World")); // 6 +console.log(message.slice(0, 5)); // "Hello" +console.log(message.includes("World")); // true +console.log(message.replace("World", "JS")); // "Hello JS" +console.log(" spaces ".trim()); // "spaces" +``` + +## 📝 Instructions: + +1. Create a string variable with a sentence. +2. Print the length of the string. +3. Print the string in uppercase and lowercase. +4. Use `indexOf()` to find the position of a word. +5. Use `slice()` to extract part of the string. +6. Use `includes()` to check if a word exists in the string. +7. Use `replace()` to replace a word with another. + +## Example: + +```js +let text = "JavaScript is amazing"; + +console.log(text.length); // 21 +console.log(text.toUpperCase()); // "JAVASCRIPT IS AMAZING" +console.log(text.indexOf("amazing")); // 14 +console.log(text.slice(0, 10)); // "JavaScript" +console.log(text.includes("amazing")); // true +console.log(text.replace("amazing", "fun")); // "JavaScript is fun" +``` + +## 💡 Hint: + ++ Strings are immutable - methods return new strings, they don't modify the original. ++ `indexOf()` returns -1 if the substring is not found. ++ Many string methods are case-sensitive! + diff --git a/exercises/25-String_methods/app.js b/exercises/25-String_methods/app.js new file mode 100644 index 00000000..c4706848 --- /dev/null +++ b/exercises/25-String_methods/app.js @@ -0,0 +1,20 @@ +//Create a string variable with a sentence +let text = ""; + +//Print the length of the string +//your code here + +//Print the string in uppercase and lowercase +//your code here + +//Use indexOf() to find the position of a word +//your code here + +//Use slice() to extract part of the string +//your code here + +//Use includes() to check if a word exists in the string +//your code here + +//Use replace() to replace a word with another +//your code here diff --git a/exercises/25-String_methods/solution.hide.js b/exercises/25-String_methods/solution.hide.js new file mode 100644 index 00000000..c1bbf62f --- /dev/null +++ b/exercises/25-String_methods/solution.hide.js @@ -0,0 +1,21 @@ +//Create a string variable with a sentence +let text = "JavaScript is awesome"; + +//Print the length of the string +console.log(text.length); + +//Print the string in uppercase and lowercase +console.log(text.toUpperCase()); +console.log(text.toLowerCase()); + +//Use indexOf() to find the position of a word +console.log(text.indexOf("awesome")); + +//Use slice() to extract part of the string +console.log(text.slice(0, 10)); + +//Use includes() to check if a word exists in the string +console.log(text.includes("awesome")); + +//Use replace() to replace a word with another +console.log(text.replace("awesome", "amazing")); diff --git a/exercises/25-String_methods/tests.js b/exercises/25-String_methods/tests.js new file mode 100644 index 00000000..c4d8e83b --- /dev/null +++ b/exercises/25-String_methods/tests.js @@ -0,0 +1,55 @@ + +const fs = require('fs'); +const path = require('path'); + +jest.dontMock('fs'); +let _buffer = ""; + +global.console.log = console.log = jest.fn((text) => _buffer += text + "\n"); + +describe('String methods exercise', function () { + afterEach(() => { jest.resetModules(); }); + + it('Should have a string variable called "text"', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/let\s+text\s*=/); + }); + + it('Should use string methods like length, toUpperCase, toLowerCase', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.length|\.toUpperCase\(\)|\.toLowerCase\(\)/); + }); + + it('Should use indexOf() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.indexOf\(/); + }); + + it('Should use slice() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.slice\(/); + }); + + it('Should use includes() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.includes\(/); + }); + + it('Should use replace() method', function () { + const appPath = path.join(__dirname, './app.js'); + const appContent = fs.readFileSync(appPath, 'utf8'); + expect(appContent).toMatch(/\.replace\(/); + }); + + it('Should print multiple values', function () { + _buffer = ""; + require('./app.js'); + const logs = _buffer.trim().split('\n'); + expect(logs.length).toBeGreaterThanOrEqual(7); + }); +});