├── README.md ├── dificil ├── adventjs │ └── exercise-4 ├── agrupar-array-por-funcion-o-propiedad ├── borde-de-asteriscos ├── celdas-iguales-ajedrez ├── innerjoin-function ├── num-opuesto-del-circulo ├── ordenar-personas-sin-mover-arboles ├── programacion-orientada-a-objetos │ ├── hotel │ └── supermercado └── revertir-caracteres-parentesis ├── facil ├── aplanar-array ├── array-con-cadenas-mas-largas ├── calcular-años-a-monto-deseado ├── calcular-cantidad-de-personas ├── calcular-comida ├── cantidad-caracteres-distintos ├── checkear-elemento-en-una-lista ├── coleccion-de-objetos-dada-una-condicion ├── contador-de-vocales ├── contar-digitos-de-num ├── crear-alarma ├── digitos-pares ├── djb2hash ├── eliminar-k-esimo ├── encontrar-primer-digito-de-string ├── es-digito ├── es-letra-o-numero ├── fuerza-brazos ├── funcion-delay ├── items-en-tesoro ├── lista-de-palabras ├── mayor-sin-mathmax ├── min-max-number ├── numero-grande-con-digitos-exactos ├── obtener-dia-actual ├── par-de-elementos-adyacentes ├── pares-e-inpares-de-un-num ├── planta-creciendo ├── prefijo-mas-largo ├── programacion-orientada-a-objetos │ └── crear-estudiante-y-no-estudiante ├── realizar-15-encuestas ├── reemplazar-numeros-en-array ├── suma-de-digitos-ingresados ├── tabla-de-multiplicacion-de-un-nro └── validar-formato-variable ├── intermedio ├── 10-random-nums ├── adventjs │ ├── exercise-1 │ ├── exercise-2 │ └── exercise-3 ├── array-numeros-consecutivos ├── bin-num-a-decimal ├── caballo-ajedrez ├── calcular-dias-vivos ├── cantidad-letras-palabras-caracteres ├── caracteres-repetidos ├── combinaciones-de-una-lista ├── convertir-array-de-numeros-a-absolutos ├── decimal-a-binario ├── digitos-consecutivos-de-string ├── elemento-cercano ├── es-palabra-palindroma ├── fantasmas-y-habitaciones-embrujadas ├── key-a-hash ├── lista-secuencial-dado-un-num ├── mac-adress ├── matrices-similares ├── max-int-eliminando-digito ├── max-suma-k-nums-consecutivos ├── maxima-absoluta-diferencia ├── modificar-prototipo-de-javascript ├── movimientos-a-array-secuencial ├── programacion-orientada-a-objetos │ ├── encuesta-de-dos-productos │ └── todo-app ├── reemplazar-letra-siguiente ├── rellenar-puertas-y-ventanas ├── saltar-obstaculos ├── subcadenas-con-longitudes ├── sumar-digitos-hasta-un-digito ├── sumar-digitos-recursiva ├── uber-costo-de-viaje ├── uber-mejor-vehiculo └── validar-ipv4 └── teoria ├── funciones-y-tipos ├── manejar-errores ├── manejar-errores-sin-trycatch ├── operadores ├── que-es-un-lenguaje-dinamico └── variable-y-tipos /README.md: -------------------------------------------------------------------------------- 1 | # Ejercicios de Javascript - dioneldev 2 | Todos los ejercicios de Javascript vistos en el canal @dioneldev ordenados por dificultades. 3 | 4 | Ejercicios resueltos en: https://www.instagram.com/dioneldev/ 5 | 6 | ## Requisitos previos 7 | Un editor de código, conceptos básicos de Javascript y muchas ganas de aprender! 8 | 9 | ## ¿Para qué sirven? 10 | Estos ejercicios son ideales para aquellos que están dispuestos a mejorar la lógica de programación y el aprendizaje del lenguaje Javascript. Dentro de las distintos niveles encontrarás ejercicios desde muy simples hasta un tanto complejos, estos pueden tener distintas soluciones. ¡Te reto a hacerlos! 11 | 12 | ## ¿Cómo resolverlos? 13 | La mejor forma es simplemente leyendo la consigna e intentar resolverlo, te aconsejo tomarte tu tiempo porque algunos ejercicios por más fáciles que parezcan a mi me han llevado hasta horas para entenderlos, recuerda que copiar y pegar código sin entenderlo no es sinónimo de aprendizaje... 14 | 15 | ## Conceptos implementados 16 | - Variables y tipos de variables 17 | - Funciones y tipos de funciones 18 | - Bucles 19 | - Operadores 20 | - Recursividad 21 | - Programación Orientada a Objetos 22 | - Métodos y prototipos 23 | - Matrices 24 | - Programación asincrónica 25 | 26 | ## ¿Qué utilizo en los videos para resolverlos? 27 | A la hora de grabarlos utilizo RunJs, aplicación de escritorio que permite tener un entorno de ejecución de código Javascript para ver los resultados en tiempo real. 28 | 29 | 30 | ---------------------------------------------------------------------------------------------- 31 | 32 | -------------------------------------------------------------------------------- /dificil/adventjs/exercise-4: -------------------------------------------------------------------------------- 1 | // En el taller de Santa 🎅, algunos mensajes navideños han sido escritos de manera peculiar: las letras dentro de los paréntesis deben ser leídas al revés 2 | 3 | // Santa necesita que estos mensajes estén correctamente formateados. Tu tarea es escribir una función que tome una cadena de texto y revierta los caracteres dentro de cada par de paréntesis, eliminando los paréntesis en el mensaje final. 4 | 5 | // Eso sí, ten en cuenta que pueden existir paréntesis anidados, por lo que debes invertir los caracteres en el orden correcto. 6 | 7 | function decode(message) { 8 | const stack = []; 9 | let words = ''; 10 | for (let i = 0; i < message.length; i++) { 11 | const letter = message[i]; 12 | if(letter === '(') { 13 | stack.push(words); 14 | words = ''; 15 | } else if (letter === ')') { 16 | words = stack.pop() + words.split("").reverse().join(""); 17 | } else { 18 | words += letter; 19 | } 20 | } 21 | return words; 22 | } 23 | 24 | const c = decode('sa(u(cla)atn)s') 25 | console.log(c) // santaclaus -------------------------------------------------------------------------------- /dificil/agrupar-array-por-funcion-o-propiedad: -------------------------------------------------------------------------------- 1 | // Haz una función que permita agrupar un array, que puede ser de valores u objetos a través de una función o de una propiedad. 2 | 3 | function solution(values, iteratee) { // iteratee es lo que se ejecuta para cada elemento 4 | const obj = {} // Debe devolver un objeto por ende creamos un objeto 5 | for(const value of values) { 6 | const key = typeof iteratee === 'function' ? iteratee(value) : value[iteratee] // metodo o accedemos a propiedad 7 | 8 | // checkear si la key esta en el objeto 9 | key in obj ? obj[key].push(value) : obj[key] = [value] 10 | } 11 | return obj; 12 | } 13 | 14 | 15 | solution([6.1, 4.2, 6.3], Math.floor) // { 6: [6.1, 6.3], 4: [4.2]} 16 | solution(['one', 'two', 'three'], 'length') // { 3: ['one', 'two'], 5: ['three'] } 17 | solution([{age: 23}, {age: 24}], 'age') // { 23: [{age: 23}], 24: [{age: 24}] } 18 | solution([ 19 | {title: 'Learning Js', rating: 8}, 20 | {title: 'Coding', rating: 10}, 21 | {title: 'Function', rating: 9} 22 | ], 'rating') // { 8: [{title: 'Learning Js', rating: 8}], 9....etc } -------------------------------------------------------------------------------- /dificil/borde-de-asteriscos: -------------------------------------------------------------------------------- 1 | // Dado un array de elementos crear un borde de asteríscos (*) para cada uno de ellos. 2 | 3 | function solution(arr) { 4 | const borderLength = arr[0].length + 2 5 | const border = '*'.repeat(borderLength) 6 | const sidesBorders = arr.map((e) => `*${e}*`) 7 | sidesBorders.unshift(border) 8 | sidesBorders.push(border) 9 | return sidesBorders 10 | } 11 | 12 | 13 | const picture = ["abc", "ded"] // [ '*****', 14 | // '*abc*', 15 | // '*ded*', 16 | // '*****'] 17 | solution(picture) -------------------------------------------------------------------------------- /dificil/celdas-iguales-ajedrez: -------------------------------------------------------------------------------- 1 | // Haz una función que determinen si el color de dos celdas dadas de un tablero de ajedrez son del mismo color 2 | 3 | function solution(cell1, cell2) { 4 | function getColumnNumber(letter) { 5 | return letter.charCodeAt(0) - 'A'.charCodeAt(0) + 1 6 | } 7 | const col1 = getColumnNumber(cell1[0]) 8 | const row1 = parseInt(cell1[1]) 9 | const col2 = getColumnNumber(cell2[0]) 10 | const row2 = parseInt(cell2[1]) 11 | 12 | return (col1 + row1) % 2 === (col2 + row2) % 2 13 | } 14 | 15 | const cell1 = "A1" 16 | const cell2 = "B2" 17 | solution(cell1, cell2) // True 18 | 19 | const cell3 = "A1" 20 | const cell4 = "H3" 21 | solution(cell3, cell4) // False -------------------------------------------------------------------------------- /dificil/innerjoin-function: -------------------------------------------------------------------------------- 1 | // Crear una función que simule un inner join con los siguientes datos 2 | 3 | const students = [ 4 | { id: 1, name: 'Alice' }, 5 | { id: 2, name: 'Bob' }, 6 | { id: 3, name: 'Charlie' }, 7 | { id: 4, name: 'David' } 8 | ] 9 | 10 | const grades = [ 11 | { studentId: 1, grade: 'A' }, 12 | { studentId: 2, grade: 'B' }, 13 | { studentId: 3, grade: 'A' }, 14 | { studentId: 5, grade: 'C' }, 15 | ] 16 | 17 | function innerJoin(leftArray, rightArray, leftKey, rightKey) { 18 | const map = new Map(); 19 | leftArray.forEach(leftEl => map.set(leftEl[leftKey], leftEl)); 20 | 21 | const output = []; 22 | rightArray.forEach(rightEl => { 23 | const leftEl = map.get(rightEl[rightKey], rightEl); 24 | if(leftEl === undefined) return; 25 | output.push({...leftEl, ...rightEl}); 26 | }) 27 | return output 28 | } 29 | 30 | innerJoin(students, grades, 'id', 'studentId') -------------------------------------------------------------------------------- /dificil/num-opuesto-del-circulo: -------------------------------------------------------------------------------- 1 | // Dado un círculo de números enteros de 0 a n-1 haz una función que encuentre el número que se encuentra en la posición opuesta al primer numero. 2 | 3 | function solution(n, firstNumber) { 4 | const halfCircle = Math.floor(n / 2) // distancia que hay que recorrer desde un número dado para llegar al número opuesto. 5 | const result = (firstNumber + halfCircle) % n // modulo n se usa para asegurar que el resultado siempre esté dentro del rango válido de índices del círculo (de 0 a n-1) si excede n-1, se "envuelva" y empiece nuevamente desde 0. 6 | return result 7 | } 8 | 9 | solution(10, 2) // 7 10 | solution(10, 7) // 2 11 | solution(4, 1) // 3 12 | 13 | // 0 - 1 - 2 - 3 - 4 14 | // | | 15 | // 9 5 16 | // | | 17 | // 8 - 7 - 6 - 5 - 4 -------------------------------------------------------------------------------- /dificil/ordenar-personas-sin-mover-arboles: -------------------------------------------------------------------------------- 1 | // Hay algunas personas paradas en el parque y se encuentran algunos árboles entre ellos que no pueden ser movidos. Tu tarea es reorganizar las personas por su altura en orden sin mover los árboles. 2 | 3 | function solution(a) { 4 | let nums = [] 5 | for(let i = 0; i < a.length; i++) { 6 | if(a[i] !== -1) { 7 | nums.push(a[i]) 8 | } 9 | } 10 | const sortedNums = nums.sort((a,b) => a - b) 11 | for(let j = 0; j < a.length; j++) { 12 | if(a[j] === -1) { 13 | sortedNums.splice(j, 0, -1) 14 | } 15 | } 16 | return sortedNums 17 | } 18 | 19 | const a = [-1, 150, 190, 170, -1, -1, 160, 180] 20 | solution(a) -------------------------------------------------------------------------------- /dificil/programacion-orientada-a-objetos/hotel: -------------------------------------------------------------------------------- 1 | class Habitacion { 2 | constructor(nro, precio) { 3 | this.nro = nro 4 | this.precio = precio 5 | this.disponible = true 6 | } 7 | detalles() { 8 | console.log(`${this.nro}: $${this.precio} ${this.disponible === true ? 'Disponible' : 'No disponible'}`) 9 | } 10 | removerReserva() { 11 | this.disponible = false 12 | } 13 | } 14 | 15 | class Hotel { 16 | static counterId = 0 17 | constructor(habitaciones = []) { 18 | this.habitaciones = habitaciones 19 | this.id = Hotel.counterId++ 20 | } 21 | reservarHabitación(nro, precio) { 22 | if(typeof nro !== 'number' || typeof precio !== 'number') throw new Error("Ingrese una habitación valida") 23 | const nuevaHabitacion = new Habitacion(nro, precio, this.disponible = true) 24 | this.habitaciones.push(nuevaHabitacion) 25 | } 26 | removerReserva(nro) { 27 | const habitacion = this.habitaciones.find(h => h.nro === nro) 28 | if(habitacion) { 29 | habitacion.removerReserva() 30 | } else { 31 | console.log("No se encontró la habitacion") 32 | } 33 | } 34 | mostrarHabitaciones() { 35 | this.habitaciones.forEach((h) => h.detalles()) 36 | } 37 | } 38 | 39 | const hotel = new Hotel() 40 | hotel.reservarHabitación(1, 10000) 41 | hotel.removerReserva(1) 42 | hotel.mostrarHabitaciones() -------------------------------------------------------------------------------- /dificil/programacion-orientada-a-objetos/supermercado: -------------------------------------------------------------------------------- 1 | // Crear un supermercado 🛒 que permita agregar productos, mostrarlos y obtener el precio total mediante la suma de ellos. 2 | 3 | // Cada producto deberá tener un identificador único, un nombre, precio y stock, también deberíamos poder obtener los detalles del producto. 4 | 5 | class Producto { 6 | constructor(id, nombre, precio, stock) { 7 | this.id = id 8 | this.nombre = nombre 9 | this.precio = precio 10 | this.stock = stock 11 | } 12 | detalles() { 13 | console.log(`${this.id}: ${this.nombre}, $${this.precio}, stock: ${this.stock}`) 14 | } 15 | } 16 | 17 | class Supermercado { 18 | constructor(productos = []) { 19 | this.productos = productos 20 | this.nextId = 1 21 | } 22 | agregarProducto(nombre, precio, stock) { 23 | if(typeof nombre !== "string" || typeof precio !== "number" || typeof stock !== "number") throw new Error("Ingrese un producto válido") 24 | // Mas validaciones, precio y stock mayor a 0 25 | const nuevoProducto = new Producto(this.nextId++, nombre, precio, stock) 26 | this.productos.push(nuevoProducto) 27 | console.log("Se añadió un nuevo producto!") 28 | } 29 | mostrarProductos() { 30 | this.productos.forEach((producto) => producto.detalles()) 31 | } 32 | } 33 | 34 | const supermarket = new Supermercado() 35 | supermarket.agregarProducto("papel", 20, 1) 36 | supermarket.agregarProducto("lapiz", 50, 5) 37 | supermarket.mostrarProductos() -------------------------------------------------------------------------------- /dificil/revertir-caracteres-parentesis: -------------------------------------------------------------------------------- 1 | // Escribir una función que revierta los carácteres en los paréntesis de un string dado. 2 | 3 | function solution(inputString) { 4 | let stack = [] 5 | let words = '' 6 | for(let i = 0; i < inputString.length; i++) { 7 | if(inputString[i] === '(') { 8 | stack.push(words) 9 | words = '' 10 | } else if(inputString[i] === ')') { 11 | words = stack.pop() + words.split("").reverse().join("") 12 | } else { 13 | words += inputString[i] 14 | } 15 | } 16 | return words 17 | } 18 | 19 | const inputString = "foo(bar)baz(blim)" 20 | solution(inputString) // "foorabbazmilb" -------------------------------------------------------------------------------- /facil/aplanar-array: -------------------------------------------------------------------------------- 1 | // Utiliza un método reduce para "aplanar" 2 | // un array de arrays en un único array que 3 | // contenga todos los elementos de los arrays origninales. 4 | 5 | function aplanar(arrays) { 6 | return arrays.reduce((acc,val) => acc.concat(val), []) 7 | } 8 | 9 | let arrays = [[1, 2, 3], [4, 5], [6]]; // → [1, 2, 3, 4, 5, 6] 10 | aplanar(arrays); -------------------------------------------------------------------------------- /facil/array-con-cadenas-mas-largas: -------------------------------------------------------------------------------- 1 | // Dado un array de strings, devolver otro array que contenga todas las cadenas más largas 2 | 3 | function solution(inputArray) { 4 | let counter = 0 5 | for(let i = 0; i < inputArray.length; i++) { 6 | if(counter < inputArray[i].length) { 7 | counter = inputArray[i].length 8 | } 9 | } 10 | return inputArray.filter(w => w.length === counter) 11 | } 12 | 13 | const inputArray = ["aba", "aa", "ad", "vcd", "aba"] 14 | solution(inputArray) // ['aba', 'vcd', 'aba'] 15 | const inputArray2 = ["aa"] 16 | solution(inputArray2) // ['aa'] -------------------------------------------------------------------------------- /facil/calcular-años-a-monto-deseado: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un monto depositado en el banco, incremente el salario cada año en base a la tasa anual, con la condición que no debes hacer ningun depósito y deberás calcular la cantidad de años que se tardará en superar el objetivo de dinero deseado. 2 | 3 | function solution(deposit, rate, goal) { 4 | if(deposit + rate === goal) return 1; 5 | const percentage = rate / 100; 6 | let counter = 0; 7 | while(deposit < goal) { 8 | deposit = deposit * percentage + deposit; 9 | counter++ 10 | } 11 | return counter; 12 | } 13 | 14 | solution(100, 20, 170) // 3 15 | solution(100, 1, 101) // 1 16 | solution(1, 100, 64) // 6 -------------------------------------------------------------------------------- /facil/calcular-cantidad-de-personas: -------------------------------------------------------------------------------- 1 | // Estas en medio de una obra de teatro y para salir hacia la salida de tu izquierda decides calcular dado una cantidad de columnas y filas totales y tu número de columna y fila donde te encuentras, la cantidad de personas que se encuentra sentada detras tuya y en la columna de la izquierda. 2 | 3 | function solution(nCols, nRows, col, row) { 4 | const $MAX_COLS = nCols; 5 | const $MAX_ROWS = nRows; 6 | if($MAX_COLS === 1 && $MAX_ROWS === 1) return 0; 7 | 8 | const TOTAL_COLS = $MAX_COLS - col; 9 | const TOTAL_ROWS = $MAX_ROWS - row; 10 | return (TOTAL_COLS * TOTAL_ROWS) + TOTAL_ROWS 11 | } 12 | 13 | solution(16, 11, 5, 3) // 96 14 | solution(1, 1, 1, 1) // 0 15 | solution(13, 6, 8 , 3) // 18 16 | -------------------------------------------------------------------------------- /facil/calcular-comida: -------------------------------------------------------------------------------- 1 | // Dado una cantidad de personas (n) y una cantidad de comida (f), calcular cuantos platos de comida serán comidos teniendo en cuenta que cada persona quiere comer lo más que pueda y cada uno deberá comer la misma cantidad que el resto. 2 | 3 | function solution(n, f) { 4 | if(n === 1 || n === f) return f; 5 | let count = 0; 6 | for(let i = n; i <= f; i += n) { 7 | count = i; 8 | } 9 | return count; 10 | } 11 | 12 | solution(9, 18) // 18 13 | solution(3, 10) // 9 14 | solution(4, 4) // 4 15 | solution(1, 2) // 2 -------------------------------------------------------------------------------- /facil/cantidad-caracteres-distintos: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un string cuente los carácteres que son distintos entre ellos 2 | 3 | function solution(str) { 4 | const charsCount = str.split("").reduce((acc, value) => { 5 | if(!acc.includes(value)) { 6 | acc.push(value) 7 | } 8 | return acc 9 | }, []) 10 | 11 | return charsCount.length 12 | } 13 | 14 | solution("cabca") // 3 -------------------------------------------------------------------------------- /facil/checkear-elemento-en-una-lista: -------------------------------------------------------------------------------- 1 | // Crear una función que reciba una lista y un valor a checkear. Devolver true si se encuentra y false si no se encuentra en la lista. 2 | 3 | function solution(list, value) { 4 | let check = false 5 | for(let i = 0; i < list.length; i++) { 6 | if(list[i] === value) { 7 | check = true 8 | } 9 | } 10 | return check 11 | } 12 | 13 | const list = [1,2,3,4] 14 | const value = 5 15 | solution(list, value) // False 16 | 17 | const listLetters = ['a','b','c'] 18 | const valueLetter = 'a' 19 | solution(listLetters, valueLetter) // true -------------------------------------------------------------------------------- /facil/coleccion-de-objetos-dada-una-condicion: -------------------------------------------------------------------------------- 1 | // Dado una matriz, crea una colección de objetos 2 | // que contengan un nombre e indiquen la cantidad 3 | // de veces que cada uno de ellos cumplan cierta condición. 4 | // La condición es n > 2 5 | // Matriz [1,2,3,4,5] 6 | 7 | const count = (matriz, callback) => { 8 | let counter = []; 9 | for(const element of matriz) { 10 | const name = callback(element) === false ? 'No cumple' : 'Cumple'; 11 | const foundName = counter.find(c => c.name === name); 12 | if(!foundName) { 13 | counter.push({name: name, count: 1}); 14 | } else { 15 | foundName.count++; 16 | } 17 | } 18 | return counter; 19 | } 20 | 21 | const matriz = [1,2,3,4,5]; 22 | console.log(count(matriz, n => n > 2)) -------------------------------------------------------------------------------- /facil/contador-de-vocales: -------------------------------------------------------------------------------- 1 | // Crear una función que cuente las vocales de una palabra ingresada 2 | 3 | function vowelsCounter(word) { 4 | const vowels = ['a','e','i','o','u', 'á', 'é', 'í', 'ó', 'ú'] 5 | let counter = 0; 6 | for(let i = 0; i < word.length; i++) { 7 | for(let j = 0; j < vowels.length; j++) { 8 | if(word[i].toLowerCase() === vowels[j]) { 9 | counter++ 10 | } 11 | } 12 | } 13 | return counter; 14 | } 15 | 16 | const word = 'Argentina es mi país' 17 | vowelsCounter(word) 18 | -------------------------------------------------------------------------------- /facil/contar-digitos-de-num: -------------------------------------------------------------------------------- 1 | // Crea una función que recibe un número entero y devuelva la cantidad de dígitos 2 | const digitCounter = (num) => { 3 | if(isNaN(num)) return "Not a number"; 4 | const digit = Math.abs(num).toString(); 5 | console.log(digit); 6 | return digit.length; 7 | } 8 | 9 | 10 | console.log(digitCounter(11241));// Crea una función que recibe un número entero y devuelva la cantidad de dígitos -------------------------------------------------------------------------------- /facil/crear-alarma: -------------------------------------------------------------------------------- 1 | // Crear una alarma 🚨 que reciba los segundos y haga una cuenta hasta que suene. 2 | 3 | function alarma(time) { 4 | let counter = 0; 5 | const id = setInterval(() => { 6 | if(counter < time) { 7 | counter++; 8 | console.log(counter) 9 | } else { 10 | console.log("Beep!") 11 | clearInterval(id) 12 | } 13 | }, 1000) 14 | } 15 | 16 | const seconds = 5; 17 | alarma(seconds) -------------------------------------------------------------------------------- /facil/digitos-pares: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva true si todos los dígitos ingresados son pares 2 | 3 | function solution(n) { 4 | const arrNums = n.toString().split("") 5 | return arrNums.every(e => e % 2 === 0 ? true : false) 6 | } 7 | const n = 248622 // TRUE 8 | const n2 = 642386 // FALSE 9 | solution(n) -------------------------------------------------------------------------------- /facil/djb2hash: -------------------------------------------------------------------------------- 1 | // Convertir una "key" en un número hash utilizando el algoritmo DJB2, y para el segundo resultado ten en cuenta que debemos reducir el valor calculado a una tabla con un tamaño de 100. 2 | // hash = 53181; 3 | // tableSize = 100; 4 | 5 | function djb2Hash(str) { 6 | let hash = 53181; 7 | for(let i = 0; i < str.length; i++) { 8 | hash = (hash * 33) + str.charCodeAt(i) 9 | } 10 | 11 | return hash; 12 | } 13 | 14 | djb2Hash("dioneldev"); 15 | let tableSize = 100; 16 | console.log(djb2Hash("dioneldev") % tableSize); -------------------------------------------------------------------------------- /facil/eliminar-k-esimo: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un arreglo de enteros, elimina cada k-ésimo elemento de él. 2 | 3 | function solution(arr, k) { 4 | const newArray = []; 5 | for(let i = 0; i < arr.length; i++) { 6 | if((i+1) % k !== 0) { 7 | newArray.push(arr[i]) 8 | } 9 | } 10 | return newArray 11 | } 12 | 13 | const inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // [ 1, 2, 4, 5, 7, 8, 10 ] 14 | const k = 3 15 | solution(inputArray, k) 16 | 17 | const inputArray2 = [2, 4, 6, 8, 10] 18 | const k2 = 2; 19 | solution(inputArray2, k2) // [ 2, 6, 10 ] -------------------------------------------------------------------------------- /facil/encontrar-primer-digito-de-string: -------------------------------------------------------------------------------- 1 | // Haz una función que encuentre el primer dígito de una cadena de texto dada. 2 | 3 | function solution(str) { 4 | const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 5 | return str.split("").find(e => nums.includes(e)) 6 | } 7 | 8 | solution("var_1__Int") // '1' -------------------------------------------------------------------------------- /facil/es-digito: -------------------------------------------------------------------------------- 1 | // Determinar con una función si el símbolo ingresado es un dígito 2 | 3 | function solution(symbol) { 4 | const condition = symbol >= '0' && symbol <= '9' 5 | return condition 6 | } 7 | 8 | 9 | solution('0') // true 10 | solution('-') // false -------------------------------------------------------------------------------- /facil/es-letra-o-numero: -------------------------------------------------------------------------------- 1 | //Crea una función que devuelva true si el string 2 | //introducido es una letra. '1' y 1 no son lo mismo. 3 | 4 | const isString = (text) => { 5 | if(!text) return false; 6 | let letters = 'abcdefghijklmnopqrstuvwxyz' 7 | if(letters.includes(text)) return true; 8 | return false; 9 | } 10 | 11 | 12 | console.log(isString("a")) //true 13 | console.log(isString("1")) //false -------------------------------------------------------------------------------- /facil/fuerza-brazos: -------------------------------------------------------------------------------- 1 | // Averiguar si la fuerza de brazos de dos personas dadas, son igualmente fuertes si pueden levantar la misma cantidad de peso y si el brazo más debil coincide con el brazo mas fuerte o el más debil del otro. 2 | 3 | function solution(yourLeft, yourRight, friendsLeft, friendsRight) { 4 | return yourLeft+yourRight === friendsLeft+friendsRight && (yourLeft === friendsLeft || yourLeft === friendsRight) 5 | } 6 | 7 | solution(10, 15, 15, 10) // true 8 | solution(10, 15, 5, 20) // false -------------------------------------------------------------------------------- /facil/funcion-delay: -------------------------------------------------------------------------------- 1 | // Crear una función delay 2 | 3 | const delay = (time) => { 4 | return new Promise(resolve => { 5 | setTimeout(() => { 6 | resolve("Promesa resuelta!"); 7 | }, time) 8 | }) 9 | } 10 | 11 | 12 | 13 | delay(3000).then(res => console.log(res)); -------------------------------------------------------------------------------- /facil/items-en-tesoro: -------------------------------------------------------------------------------- 1 | // Haz una función que dado dos items encontrados en un tesoro con sus respectivos pesos y valores, calcular el máximo valor de items que puedes llevar teniendo en cuenta tu capacidad máxima de peso. 2 | // No puedes llevar más de un item del mismo tipo. 3 | 4 | function solution(v1, w1, v2, w2, maxW) { 5 | if(w1 + w2 <= maxW) { 6 | return v1 + v2; 7 | } else if(w1 <= maxW && w2 > maxW) { 8 | return v1; 9 | } else if(w2 <= maxW && w1 > maxW) { 10 | return v2; 11 | } else if(w1 <= maxW && w2 <= maxW) { 12 | return Math.max(v1, v2) 13 | } else { 14 | return 0; 15 | } 16 | } 17 | 18 | const value1 = 10; 19 | const weight1 = 5; 20 | const value2 = 6; 21 | const weight2 = 4; 22 | const maxW = 8; 23 | solution(value1, weight1, value2, weight2, maxW) // 10 24 | solution(10, 5, 6, 4, 9) // 16 25 | solution(10, 2, 11, 3, 1) // 0 26 | solution(15, 2, 20, 3, 2) // 15 -------------------------------------------------------------------------------- /facil/lista-de-palabras: -------------------------------------------------------------------------------- 1 | // Haz una función que reciba una serie de palabras separadas por espacios y conviértelo a una lista con esos elementos. 2 | 3 | function solution(words) { 4 | return words.split(" ").map((w, i) => { 5 | return { 6 | index: i + 1, 7 | word: w 8 | } 9 | }) 10 | } 11 | 12 | const words = "Hoy es un día de mucha programación" 13 | solution(words) -------------------------------------------------------------------------------- /facil/mayor-sin-mathmax: -------------------------------------------------------------------------------- 1 | // Escribir una función findMax que reciba un 2 | // array de numeros y devuelva el mayor. 3 | // ¡ NO PUEDES USAR MATH.MAX ! 4 | const findMax = (arrayOfNums) => { 5 | let result = -Infinity; 6 | for(let i = 0; i < arrayOfNums.length; i++) { 7 | let number = arrayOfNums[i]; 8 | if(number > result) { 9 | result =+ number; 10 | } 11 | } 12 | return Math.floor(result); 13 | } 14 | 15 | const arr = [-8,-2,-13,-44,-5182]; 16 | console.log(findMax(arr)) 17 | 18 | // Con math.max 19 | const findMaxWithMax = (array) => { 20 | const maxNumber = Math.max(...array); 21 | return maxNumber 22 | } 23 | const arrOfNumbers = [10,29,48,32,58] 24 | console.log(findMaxWithMax(arrOfNumbers)); -------------------------------------------------------------------------------- /facil/min-max-number: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva el número menor y mayor de un array de números 2 | 3 | function solution(numbers) { 4 | 5 | const max = Math.max(...numbers); 6 | 7 | let minNum = Infinity; 8 | for(let i = 0; i < numbers.length; i++) { 9 | if(minNum > numbers[i]) { 10 | minNum = numbers[i] 11 | } 12 | } 13 | return { 14 | min: minNum, 15 | max: max 16 | } 17 | } 18 | 19 | const numbers = [25,79,129,50,2] // min: 2 , max: 129 20 | solution(numbers) -------------------------------------------------------------------------------- /facil/numero-grande-con-digitos-exactos: -------------------------------------------------------------------------------- 1 | // Dado un n° entero devolver el número más grande que contenga la cantidad exacta de dígitos dados. 2 | 3 | function solution(n) { 4 | let arr = Array.from({length: 1}, () => Array(n).fill(9)); 5 | console.log(arr); 6 | return Number(arr[0].join("")); 7 | } 8 | 9 | solution(2) // 99 10 | solution(4) // 9999 -------------------------------------------------------------------------------- /facil/obtener-dia-actual: -------------------------------------------------------------------------------- 1 | // Crear una función para obtener el nombre del día actual 2 | // Ejemplo "Viernes" 3 | 4 | const dayName = ["Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado"] 5 | 6 | function getDayName(num) { 7 | if(num > 6) throw new Error("Error al obtener el día") 8 | return dayName[num] 9 | } 10 | 11 | const date = new Date().getDay(); 12 | getDayName(date) -------------------------------------------------------------------------------- /facil/par-de-elementos-adyacentes: -------------------------------------------------------------------------------- 1 | // Dado un array de enteros encuentra el par 2 | // de elementos adyacentes que tenga el producto 3 | // más grande y devuelva el producto 4 | 5 | function solution(inputArray) { 6 | let total = -Infinity; 7 | for(let i = 0; i < inputArray.length; i++) { 8 | if(inputArray[i] * inputArray[i+1] > total) total = inputArray[i] * inputArray[i+1]; 9 | } 10 | return total; 11 | } 12 | 13 | const inputArray = [3, 6, -2, -5, 7, 3] 14 | solution(inputArray) -------------------------------------------------------------------------------- /facil/pares-e-inpares-de-un-num: -------------------------------------------------------------------------------- 1 | // Crear una función que devuelva todos los números pares e impares de un número 2 | 3 | function solution(num) { 4 | let even = [] 5 | let odd = [] 6 | 7 | let start = num < 0 ? num : 0 8 | let end = num > 0 ? num : 0 9 | 10 | for(let i = start; i < end; i++) { 11 | if(i % 2 === 0) { 12 | even.push(i) 13 | } else { 14 | odd.push(i) 15 | } 16 | } 17 | return ( 18 | `Even numbers = ${even} \n Odd numbers: ${odd}`) 19 | } 20 | 21 | const num = -24 22 | solution(num) -------------------------------------------------------------------------------- /facil/planta-creciendo: -------------------------------------------------------------------------------- 1 | // Haz una función que dada una planta que crece constantemente y una velocidad de crecimiento y de decrecimiento calcular cuántos días deberá crecer hasta la altura deseada. 2 | 3 | // ¡La planta crece de día y decrece de noche! 4 | 5 | function solution(upSpeed, downSpeed, desiredHeight) { 6 | let height = 0; 7 | let days = 0; 8 | while(height < desiredHeight) { 9 | days++; 10 | height += upSpeed; 11 | if(height >= desiredHeight) break; 12 | height -= downSpeed; 13 | } 14 | return days; 15 | } 16 | 17 | const desiredHeight = 910; 18 | const upSpeed = 100; 19 | const downSpeed = 10; 20 | solution(upSpeed, downSpeed, desiredHeight) // 10 21 | 22 | const desiredHeight2 = 4; 23 | const upSpeed2 = 10; 24 | const downSpeed2 = 9; 25 | solution(upSpeed2, downSpeed2, desiredHeight2) // 1 -------------------------------------------------------------------------------- /facil/prefijo-mas-largo: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un string devuelva el prefijo más largo que contenga únicamente números 2 | 3 | function solution(str) { 4 | let nums = ""; 5 | for(let i = 0; i < str.length; i++) { 6 | if(str[i] >= '0' && str[i] <= '9') { 7 | nums += str[i] 8 | } else { 9 | break; 10 | } 11 | } 12 | return nums; 13 | } 14 | 15 | solution("123aa1") // 123 16 | solution("0123456789") // 0123456789 17 | solution("aaaaaaa") // "" 18 | -------------------------------------------------------------------------------- /facil/programacion-orientada-a-objetos/crear-estudiante-y-no-estudiante: -------------------------------------------------------------------------------- 1 | // Crear dos personas, una que esté estudiando y otra que no. 2 | // Debe contener nombre, edad, género y la carrera. 3 | 4 | class Persona { 5 | constructor(nombre, edad, genero) { 6 | this.nombre = nombre 7 | this.edad = edad 8 | this.genero = genero 9 | } 10 | saludar() { 11 | console.log(`Hola soy ${this.nombre} y tengo ${this.edad} años.`) 12 | } 13 | } 14 | 15 | class Estudiante extends Persona { 16 | constructor(nombre, edad, genero, carrera) { 17 | super(nombre, edad, genero) 18 | this.carrera = carrera 19 | } 20 | estudios() { 21 | super.saludar() 22 | console.log( `Me encuentro estudiando ${this.carrera}`) 23 | } 24 | } 25 | 26 | const persona = new Persona('Martin', 20, 'Masculino') 27 | persona.saludar() 28 | 29 | const estudiante = new Estudiante('Pablo', 25, 'Masculino', 'Programación') 30 | estudiante.estudios() -------------------------------------------------------------------------------- /facil/realizar-15-encuestas: -------------------------------------------------------------------------------- 1 | // Realizar 15 encuestas de dos productos donde cada uno de ellos va a recibir una calificación aleatoria, devolver el producto con mejor promedio y su promedio. 2 | 3 | function encuesta() { 4 | const productoA = []; 5 | const productoB = []; 6 | let sumaA = 0; 7 | let sumaB = 0; 8 | 9 | for(let i = 0; i < 15; i++) { 10 | const numA = Math.floor(Math.random() * 100 + 1) // 1 - 100 11 | const numB = Math.floor(Math.random() * 100 + 1) 12 | productoA.push(numA) 13 | productoB.push(numB) 14 | sumaA += numA 15 | sumaB += numB 16 | } 17 | 18 | let promedioA = Math.floor(sumaA / 15); 19 | let promedioB = Math.floor(sumaB / 15); 20 | if(promedioA > promedioB) { 21 | console.log(`El producto A tiene mejores valoraciones que el producto B con un promedio de ${promedioA}`) 22 | } else { 23 | console.log(`El producto B tiene mejores valoraciones que el producto A con un promedio de ${promedioB}`) 24 | } 25 | } 26 | 27 | encuesta() -------------------------------------------------------------------------------- /facil/reemplazar-numeros-en-array: -------------------------------------------------------------------------------- 1 | // Haz una función que reemplace en el array los números a reemplazar 2 | 3 | function solution(arr, numToReplace, substitutionNum) { 4 | for(let i = 0; i < arr.length; i++) { 5 | if(arr[i] === numToReplace) { 6 | arr.splice(i, 1, substitutionNum) 7 | } 8 | } 9 | return arr 10 | } 11 | 12 | function solution2(arr, numToReplace, substitutionNum) { 13 | return arr.map(e => e === numToReplace ? substitutionNum : e) 14 | } 15 | 16 | const arr = [1, 2, 1] 17 | const numToReplace = 1; 18 | const substitutionNum = 3; 19 | solution2(arr, numToReplace, substitutionNum) // [3,2,3] -------------------------------------------------------------------------------- /facil/suma-de-digitos-ingresados: -------------------------------------------------------------------------------- 1 | // Crear una función que devuelva la suma de los dígitos ingresados. 2 | 3 | function solution(n) { 4 | return n.toString().split("").reduce((acc, value) => acc + Number(value) ,0) 5 | } 6 | 7 | solution(29) // 11 8 | solution(123) // 6 -------------------------------------------------------------------------------- /facil/tabla-de-multiplicacion-de-un-nro: -------------------------------------------------------------------------------- 1 | // Crear una función que devuelva la tabla de multiplicación de un número 2 | 3 | function multiplicar(num) { 4 | if(num <= 0) return 0; 5 | const nros = [] 6 | for(let i = 1; i < 11; i++) { 7 | nros.push(num * i) 8 | } 9 | 10 | return nros; 11 | } 12 | 13 | const $num = 2; 14 | multiplicar($num) -------------------------------------------------------------------------------- /facil/validar-formato-variable: -------------------------------------------------------------------------------- 1 | // Haz una función que valide que el nombre ingresado tenga un formato "variable" 2 | 3 | function solution(name) { 4 | const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/; // solo letras inglesas, dígitos y guiones bajos, y no puede comenzar con un dígito 5 | return regex.test(name); 6 | } 7 | 8 | // ^[a-zA-Z_]: El nombre debe comenzar con una letra (mayúscula o minúscula) o un guion bajo. 9 | // [a-zA-Z0-9_]*$: El resto del nombre puede contener letras, dígitos o guiones bajos (cero o más veces). 10 | 11 | const name = "var_1__Int" // True 12 | const name2 = "qq-q" // False 13 | const name3 = "2w2" // False 14 | solution(name2) -------------------------------------------------------------------------------- /intermedio/10-random-nums: -------------------------------------------------------------------------------- 1 | // Haz una función que rellene un array de números con otros 10 números al azar entre el 1 al 25, ordenados de menor a mayor y los números no deben repetirse. 2 | 3 | function solution(nums) { 4 | const newNums = [...nums] 5 | const arrLength = nums.length + 10; 6 | while(newNums.length !== arrLength) { 7 | let num = Math.floor(Math.random() * 25 + 1); 8 | if(!newNums.includes(num)) { 9 | newNums.push(num) 10 | } 11 | } 12 | 13 | return newNums.sort((a,b) => a-b); 14 | } 15 | 16 | const numbers = [9, 22, 10, 5] 17 | solution(numbers) -------------------------------------------------------------------------------- /intermedio/adventjs/exercise-1: -------------------------------------------------------------------------------- 1 | //En la fábrica de juguetes del Polo Norte, cada juguete tiene un número de identificación único. 2 | //Sin embargo, debido a un error en la máquina de juguetes, algunos números se han asignado a más de un juguete. 3 | //¡Encuentra el primer número de identificación que se ha repetido, donde la segunda ocurrencia tenga el índice //más pequeño! 4 | //En otras palabras, si hay más de un número repetido, debes devolver el número cuya segunda ocurrencia aparezca //primero en la lista. Si no hay números repetidos, devuelve -1. 5 | 6 | // Primera forma (SET) 7 | const findFirstRepeated = (gifts) => { 8 | let nums = new Set(); 9 | for(let i = 0; i < gifts.length; i++) { 10 | const num = gifts[i]; 11 | if(nums.has(num)) return num; 12 | nums.add(num); 13 | } 14 | return -1; 15 | } 16 | 17 | // Segunda forma (object) 18 | const findFirstRepeatedWobject = (gifts) => { 19 | let numbs = {}; 20 | for(let i = 0; i < gifts.length; i++) { 21 | const num = gifts[i]; 22 | if(numbs[num] !== undefined) return num; 23 | numbs[num] += num 24 | } 25 | return -1; 26 | } 27 | 28 | // Tercera forma array 29 | function findFirstRepeatedArr(gifts) { 30 | const results = []; 31 | for (let i = 0; i < gifts.length; i++) { 32 | if(results.includes(gifts[i])) return gifts[i]; 33 | 34 | results.push(gifts[i]); 35 | } 36 | return -1; 37 | } 38 | 39 | 40 | 41 | // TESTS ! 42 | const giftIds = [2, 1, 3, 5, 3, 2] 43 | const firstRepeatedId = findFirstRepeatedWobject(giftIds) 44 | console.log(firstRepeatedId) // 3 45 | // Aunque el 2 y el 3 se repiten 46 | // el 3 aparece primero por segunda vez 47 | 48 | const giftIds2 = [1, 2, 3, 4] 49 | const firstRepeatedId2 = findFirstRepeatedWobject(giftIds2) 50 | console.log(firstRepeatedId2) // -1 51 | // Es -1 ya que no se repite ningún número 52 | 53 | const giftIds3 = [5, 1, 5, 1] 54 | const firstRepeatedId3 = findFirstRepeated(giftIds3) 55 | console.log(firstRepeatedId3) -------------------------------------------------------------------------------- /intermedio/adventjs/exercise-2: -------------------------------------------------------------------------------- 1 | // En el taller de santa los elfos, 2 | // tienen una lista de regalos que 3 | // desean fabricar y un conjunto 4 | // limitado de materiales. 5 | 6 | // Escribir una función que dada una 7 | // lista de regalos y los materiales 8 | // disponibles, devuelva una lista de 9 | // los regalos que se pueden fabricar. 10 | 11 | const manufacture = (gifts, materials) => { 12 | return gifts.filter(gift => { 13 | return gift.split("").every(letter => materials.includes(letter)); 14 | }) 15 | } 16 | 17 | 18 | 19 | const gifts = ['juego', 'puzzle'] 20 | const materials = 'jlepuz' 21 | 22 | manufacture(gifts, materials); // 'puzzle' -------------------------------------------------------------------------------- /intermedio/adventjs/exercise-3: -------------------------------------------------------------------------------- 1 | // Tu tarea es escribir una función que identifique y devuelva el primer paso extra que se ha añadido o eliminado en la cadena de fabricación. Si no hay ninguna diferencia entre las secuencias, devuelve una cadena vacía. 2 | 3 | function findNaughtyStep(original, modified) { 4 | if(original.length === modified.length) return ''; 5 | 6 | const largeString = Math.max(original.length, modified.length); 7 | 8 | for(let i = 0; i < largeString; i++) { 9 | if(original[i] !== modified[i]) return modified.length > original.length ? 10 | modified[i] : original[i] 11 | } 12 | return '' 13 | } 14 | 15 | const original = 'stepfor' 16 | const modified = 'stepor' 17 | findNaughtyStep(original, modified) // 'f' -------------------------------------------------------------------------------- /intermedio/array-numeros-consecutivos: -------------------------------------------------------------------------------- 1 | // Dado una secuencia de enteros en un array determinar si es posible obtener un array de números consecutivos removiendo no más de un elemento. 2 | // En ese caso devolver true y de lo contrario devolver false. 3 | 4 | const solution = (array) => { 5 | let counter = 0; 6 | for(let i = 0; i < array.length; i++) { 7 | if(array[i] <= array[i-1]) { 8 | counter++ 9 | if(array[i] <= array[i-2] && array[i+1] <= array[i-1]) return false; 10 | } 11 | } 12 | return counter <= 1; 13 | } 14 | 15 | 16 | 17 | // TESTS 18 | console.log(solution([1, 3, 2, 1])); // False 19 | console.log(solution([1,3,2])) // true 20 | console.log(solution([3, 6, 5, 8, 10, 20, 15])) // False 21 | console.log(solution([1, 2, 1, 2])) // False 22 | -------------------------------------------------------------------------------- /intermedio/bin-num-a-decimal: -------------------------------------------------------------------------------- 1 | // Haz una función que convierta un número binario a decimal 2 | 3 | function solution(binNum) { 4 | //return parseInt(binNum, 2); 5 | let decimal = 0; 6 | let base = 1; 7 | 8 | for(let i = binNum.length - 1; i >= 0; i--){ // recorremos desde final a principio 9 | const digit = binNum[i]; 10 | if(digit === '1') { 11 | decimal += base; 12 | } 13 | base *= 2; // Multiplica la base por 2 para la siguiente posición. 14 | } 15 | return decimal; 16 | } 17 | 18 | solution('1010000111001101') // 41421 19 | solution('11111111') // 255 -------------------------------------------------------------------------------- /intermedio/caballo-ajedrez: -------------------------------------------------------------------------------- 1 | // En un tablero de ajedrez queremos calcular la cantidad de movimientos que puede hacer un caballo a partir de una celda dada que es donde se encuentra. 2 | 3 | function solution(cell) { 4 | const column = cell.charCodeAt(0) - 'a'.charCodeAt(0) + 1; 5 | const row = parseInt(cell[1]); 6 | 7 | const knightMoves = [ 8 | [2, 1], [2, -1], [1, -2], [1, 2], [-2, 1], [-2, -1], [-1, 2], [-1, -2] 9 | ] 10 | 11 | let validMoves = 0; 12 | for(const move of knightMoves) { 13 | const newX = column + move[1]; 14 | const newY = row + move[0] 15 | if(newX >= 1 && newX <= 8 && newY >= 1 && newY <= 8) { 16 | console.log(move) // [2, 1] [1, 2] 17 | validMoves++; 18 | } 19 | } 20 | return validMoves; 21 | } 22 | 23 | solution("a1") // 2 -------------------------------------------------------------------------------- /intermedio/calcular-dias-vivos: -------------------------------------------------------------------------------- 1 | // Crear una función que calcule la cantidad de días que llevamos vivos a partir de una fecha dada. 2 | 3 | function calculateDaysLived(birthDate) { 4 | const today = new Date() 5 | const birthTime = birthDate.getTime() 6 | const todayTime = today.getTime() 7 | const differenceTime = todayTime - birthTime 8 | 9 | const daysLived = Math.floor(differenceTime / (1000 * 60 * 60 * 24)) 10 | return daysLived 11 | } 12 | 13 | 14 | const birthDate = new Date('2004-04-18'); 15 | calculateDaysLived(birthDate); -------------------------------------------------------------------------------- /intermedio/cantidad-letras-palabras-caracteres: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva la cantidad de palabras, letras, y carácteres de una oración. 2 | 3 | function solution(words) { 4 | const wordsCount = words.split(" ").filter(word => word.match(/^[a-zA-Z]/)).length 5 | 6 | const letterRegex = /[a-zA-Z]/g; 7 | const letterMatches = words.match(letterRegex); 8 | 9 | const specialCharsRegex = /[!@#\$%\^\&*\,)\(+=._-]/g; 10 | const specialChars = words.match(specialCharsRegex); 11 | 12 | return { 13 | wordsCount: wordsCount, 14 | chracters: words.length, 15 | letters: letterMatches ? letterMatches.length : "No contiene letras", 16 | specialChars: specialChars ? specialChars.length : "No contiene carácteres especiales" 17 | } 18 | } 19 | 20 | const words = "Estamos resolviendo 1 ejercicio de Javascript, bastante simple." 21 | solution(words) -------------------------------------------------------------------------------- /intermedio/caracteres-repetidos: -------------------------------------------------------------------------------- 1 | // Dado dos cadenas de texto, encontrar el número de carácteres que se repiten entre sí. 2 | 3 | function solution(s1, s2) { 4 | const firstWord = s1.split("") 5 | const secondWord = s2.split("") 6 | 7 | let counter = 0; 8 | 9 | for(let i = 0; i < firstWord.length; i++) { 10 | for(let j = 0; j < secondWord.length; j++) { 11 | if(firstWord[i] === secondWord[j]) { 12 | counter++ 13 | secondWord.splice(j, 1) 14 | break; 15 | } 16 | } 17 | } 18 | 19 | return counter 20 | } 21 | 22 | const s1 = "aabcc" 23 | const s2 = "adcaa" 24 | solution(s1, s2) // 3 => a a c -------------------------------------------------------------------------------- /intermedio/combinaciones-de-una-lista: -------------------------------------------------------------------------------- 1 | // Crear una función que devuelva todas las combinaciones posibles de una lista recibida por parámetros. 2 | 3 | function solution(list) { 4 | const results = [] 5 | for(let i = 0; i < list.length; i++) { 6 | for(let j = 0; j < list.length; j++) { 7 | results.push([list[i], list[j]]) 8 | } 9 | } 10 | return results 11 | } 12 | 13 | const list = ['mandarina', 'naranja', 'banana'] 14 | solution(list) -------------------------------------------------------------------------------- /intermedio/convertir-array-de-numeros-a-absolutos: -------------------------------------------------------------------------------- 1 | // Crear una función convertir que convierta un array de números consecutivos a un array de números absolutos. 2 | 3 | const convert = (nums) => { 4 | return nums.reduce((acc, value) => { 5 | return acc.concat(acc[acc.length - 1] + value); 6 | }, [nums[0]]) 7 | } 8 | // acc (2) = 2 9 | // acc (2) + value (2) = 4 10 | // acc(4) + value (2) = 6 11 | // acc(6) + value (3) = 9 12 | // acc(9) + value (1) = 10 13 | 14 | 15 | const arrayOfNums = [2,2,3,1] //[ 2, 4, 6, 9, 10 ] 16 | convert(arrayOfNums); -------------------------------------------------------------------------------- /intermedio/decimal-a-binario: -------------------------------------------------------------------------------- 1 | // Crear una función que convierta un número decimal a binario 2 | 3 | function convert(num) { 4 | if(num <= 0) return 0 5 | let binario = "" 6 | let count = num 7 | while(count > 0) { 8 | binario += count % 2 9 | count = Math.floor(count / 2) 10 | } 11 | return binario 12 | } 13 | 14 | const num = 13 15 | convert(num) // 1011 -------------------------------------------------------------------------------- /intermedio/digitos-consecutivos-de-string: -------------------------------------------------------------------------------- 1 | // Haz una función que encuentre la mayor cantidad de dígitos consecutivos dado un string 2 | 3 | function solution(str) { 4 | let currentDigits = "" 5 | let result = "" 6 | 7 | for(let i = 0; i < str.length; i++) { 8 | if(str[i] >= '0' && str[i] <= '9') { 9 | currentDigits += str[i] 10 | } else { 11 | if(result.length < currentDigits.length) { 12 | result = currentDigits; 13 | } 14 | currentDigits = ""; 15 | } 16 | } 17 | 18 | // Check the last currentDigits 19 | if(currentDigits.length > result.length) { 20 | result = currentDigits; 21 | } 22 | return result; 23 | } 24 | 25 | solution("123aa1") // "123" 26 | solution("123aaa53828") // "53828" 27 | solution("a652a69192a56834832aa23") // "56834832" 28 | solution("0123456789"); // "0123456789" 29 | solution("aaaaaaa"); // "" -------------------------------------------------------------------------------- /intermedio/elemento-cercano: -------------------------------------------------------------------------------- 1 | // Haz una función que determine qué elemento de la matríz es el más cercano a todos los demás valores que minimiza la siguiente suma: 2 | // S(x)=∣a[0]−x∣+∣a[1]−x∣+...+∣a[n−1]−x∣ 3 | 4 | // x = 2 => ∣2−2∣+∣4−2∣+∣7−2∣=0+2+5=7 5 | // x = 4 => ∣2−4∣+∣4−4∣+∣7−4∣=2+0+3=5 6 | // x = 7 => ∣2−7∣+∣4−7∣+∣7−7∣=5+3+0=8 7 | 8 | // Mediana: En un array ordenado, el elemento que minimiza la suma de las diferencias absolutas con todos los demás elementos es la mediana. Esto se debe a la naturaleza de la función de valor absoluto. 9 | 10 | function solution(a) { 11 | if(a.length <= 1) return a[0] 12 | const midIndex = Math.floor((a.length - 1) / 2 ); 13 | return a[midIndex] 14 | } 15 | 16 | solution([2, 4, 7]) // 4 17 | solution([2, 3]) // 2 18 | solution([23]) // 23 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /intermedio/es-palabra-palindroma: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva true en caso de que los carácteres puedan ser reordenados para formar una palabra palindroma. 2 | 3 | function solution(word) { 4 | const charCount = new Map() 5 | for(let i = 0; i < word.length; i++) { 6 | if(charCount.has(word[i])) { 7 | charCount.set(word[i], charCount.get(word[i] + 1)) 8 | } else { 9 | charCount.set(word[i], 1) 10 | } 11 | } 12 | let counter = 0 13 | for(values of charCount.values()) { 14 | if(values % 2 === 0) { 15 | counter++ 16 | } 17 | } 18 | 19 | return counter <= 1 20 | } 21 | 22 | const word = 'aabb' 23 | solution(word) // True => abba -------------------------------------------------------------------------------- /intermedio/fantasmas-y-habitaciones-embrujadas: -------------------------------------------------------------------------------- 1 | // Los fantasmas están mundándose a una nueva construcción la cual tiene un conjunto de habitaciones y tiene un costo diferente, alguna de ellas tienen coste cero pero hay un rumor de que todas las habitaciones gratis están embrujadas, los fantasmas se niegan a pasar por ellas y las que se encuentren por debajo. 2 | 3 | // Dado una matríz de enteros, donde cada valor representa el costo de la habitación, debes devolver la suma total de todas las habitaciones que son adecuadas para los fantasmas. 4 | 5 | // |👻|1️⃣|1️⃣|2️⃣| 6 | // |👻|5️⃣|👻|👻| 7 | // |2️⃣|👻|3️⃣|3️⃣| 8 | 9 | function solution(matrix) { 10 | let total = 0 11 | console.log(matrix[0].length) // 4 => 4 columnas 12 | console.log(matrix.length) // 3 => 3 filas 13 | 14 | for (let i = 0; i < matrix[0].length; i++) { // Accedemos a la primer columna de la matriz 15 | for (let j = 0; j < matrix.length; j++) { // Navegamos por cada habitación verticalmente 16 | if (matrix[j][i] === 0) { 17 | // Esta habitación esta embrujada, entonces no importarán las habitaciones debajo. 18 | // Continuar a la siguiente columna de habitaciones 19 | break; 20 | } 21 | total += matrix[j][i]; 22 | } 23 | } 24 | return total; 25 | } 26 | 27 | const matrix = [[0, 1, 1, 2], 28 | [0, 5, 0, 0], 29 | [2, 0, 3, 3]] 30 | 31 | solution(matrix) // 9 32 | -------------------------------------------------------------------------------- /intermedio/key-a-hash: -------------------------------------------------------------------------------- 1 | // Convertir una "key" en un número hash utilizando el algoritmo DJB2, y para el segundo resultado ten en cuenta que debemos reducir el valor calculado a una tabla con un tamaño de 100. 2 | // hash = 53181; 3 | // tableSize = 100; 4 | 5 | function djb2Hash(str) { 6 | let hash = 5381; 7 | for(let i = 0; i < str.length; i++) { 8 | hash = (hash * 33) + str.charCodeAt(i); // La multiplicación por 33 y el uso de charCodeAt son parte de su mecanismo para generar un valor hash a partir de una cadena de texto. 9 | } 10 | 11 | return hash; 12 | } 13 | 14 | let tableSize = 100; 15 | djb2Hash("dioneldev") // 249885461146855140 16 | console.log(djb2Hash("programar") % tableSize) // 16 17 | 18 | 19 | function hash(str) { 20 | let hash = 0; 21 | let tableSize = 10; 22 | for(let i = 0; i < str.length; i++) { 23 | hash += str.charCodeAt(i) 24 | } 25 | return hash % 10; 26 | } 27 | hash("marcos") // 5 -------------------------------------------------------------------------------- /intermedio/lista-secuencial-dado-un-num: -------------------------------------------------------------------------------- 1 | // Generar una lista de números secuencial usando bucles anidados a partir de un número recibido. El n° recibido será dividido por dos hasta llegar a uno. 2 | 3 | function solution(n) { 4 | const results = [] 5 | for(let i = 0; i < n; i++) { 6 | for(let j = n; j > 0; j = parseInt(j / 2)) { 7 | results.push(j) 8 | } 9 | } 10 | return results 11 | } 12 | 13 | solution(4) -------------------------------------------------------------------------------- /intermedio/mac-adress: -------------------------------------------------------------------------------- 1 | // Verifica si la MAC Adress es correcta o incorrecta, teniendo en cuenta que debe contener números del 0 al 9 y letras de la A a la F. 2 | 3 | function solution(inputString) { 4 | const segments = inputString.split("-") 5 | if(segments.length !== 6) return false; 6 | 7 | for(let i = 0; i < segments.length; i++) { 8 | const firstPart = segments[i][0] 9 | const secondPart = segments[i][1] 10 | if(!((firstPart >= '0' && firstPart <= '9') || (firstPart >= 'A' && firstPart <= 'F'))) { 11 | return false; 12 | } 13 | if(!((secondPart >= '0' && secondPart <= '9') || (secondPart >= 'A' && secondPart <= 'F'))) { 14 | return false; 15 | } 16 | } 17 | return true; 18 | } 19 | 20 | // Solución 2 21 | function solution2(inputString) { 22 | const macRegex = /^([0-9A-F]{2}-){5}[0-9A-F]{2}$/; 23 | return macRegex.test(inputString); 24 | } 25 | 26 | 27 | solution("00-1B-63-84-45-E6") // true 28 | solution("Z1-1B-63-84-45-E6") // false 29 | solution("not a MAC-48 address") // false 30 | solution("12-34-56-78-9A-BG") // false -------------------------------------------------------------------------------- /intermedio/matrices-similares: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva True o False si dos matrices son "similares" (si una de ellas puede ser obtenida de almenos un intercambio de un par de elementos). 2 | 3 | function solution(a,b) { 4 | if(a.length !== b.length) return false 5 | const diffPositions = [] 6 | for(let i = 0; i < a.length; i++) { 7 | if(a[i] !== b[i]) { 8 | diffPositions.push([a[i], b[i]]) 9 | } 10 | } 11 | if(diffPositions.length === 0) return true 12 | if(diffPositions.length !== 2) return false 13 | return diffPositions[0][0] === diffPositions[1][1] && diffPositions[0][1] === diffPositions[1][0] 14 | } 15 | 16 | const a = [1,2,3] 17 | const b = [2,1,3] 18 | solution(a,b) // TRUE -------------------------------------------------------------------------------- /intermedio/max-int-eliminando-digito: -------------------------------------------------------------------------------- 1 | // Dado un entero encuentre el máximo número que puedes obtener eliminando únicamente un dígito. 2 | 3 | function solution(num) { 4 | let nums = num.toString(); 5 | let maxNum = -Infinity; 6 | 7 | for(let i = 0; i < nums.length; i++) { 8 | const newNumStr = nums.slice(0, i) + nums.slice(i+1) 9 | if(Number(newNumStr) > maxNum) { 10 | maxNum = Number(newNumStr); 11 | } 12 | } 13 | return maxNum; 14 | } 15 | 16 | solution(152) // 52 17 | solution(1001) // 101 -------------------------------------------------------------------------------- /intermedio/max-suma-k-nums-consecutivos: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un array de números enteros, encuentre la máxima suma posible de "k" números consecutivos. 2 | 3 | function solution(arr, k) { 4 | if(arr.length < k) return null; 5 | 6 | let sum = 0; 7 | for(let i = 0; i < k; i++) { // Suma los primeros 'k' números 8 | sum += arr[i] 9 | } 10 | 11 | let currentSum = sum; 12 | for(let i = k; i < arr.length; i++) { // Empieza en el 'k' número 13 | currentSum += arr[i] - arr[i-k] 14 | // 5 + 5 - 2 = 8 15 | // 8 + 1 - 3 = 6 16 | // 6 + 6 - 5 = 7 17 | console.log(currentSum) 18 | sum = Math.max(sum, currentSum) 19 | } 20 | return sum; 21 | } 22 | 23 | solution([2,3,5,1,6] , 2) // 8 24 | solution([1, 3, 2, 4], 3) // 9 25 | -------------------------------------------------------------------------------- /intermedio/maxima-absoluta-diferencia: -------------------------------------------------------------------------------- 1 | // Dado un array de números enteros, encontrar la máxima absoluta diferencia entre dos elementos adyacentes. 2 | 3 | function solution(arr) { 4 | let diff = 0 5 | for(let i = 0; i < arr.length; i++) { 6 | const actualDiff = Math.abs(arr[i-1] - arr[i]) 7 | if(diff < actualDiff) { 8 | diff = actualDiff 9 | } 10 | } 11 | return diff 12 | } 13 | 14 | 15 | const arr = [2, 4, 1, 0] 16 | const arr2 = [10, 11, 13] 17 | solution(arr) // 3 18 | solution(arr2) // 2 -------------------------------------------------------------------------------- /intermedio/modificar-prototipo-de-javascript: -------------------------------------------------------------------------------- 1 | // Modificar el funcionamiento de Javascript en un objeto y en un array (PROTOTYPES) 2 | 3 | // Modificando el prototipo de un Objeto 4 | let obj = { 5 | name: 'Marcos', 6 | age: 20, 7 | changeName: function(name) { 8 | this.name = name 9 | } 10 | } 11 | 12 | obj.changeName('Diego') 13 | obj.name // 'Diego' 14 | 15 | 16 | // Modificar el prototipo de un Array 17 | const nums = [1, 2, 3, 4, 5] 18 | Array.prototype.sumar = function() { 19 | let resultado = 0; 20 | for(let i = 0; i < this.length; i++) { 21 | resultado += this[i] 22 | } 23 | return resultado 24 | } 25 | 26 | nums.sumar() // 15 -------------------------------------------------------------------------------- /intermedio/movimientos-a-array-secuencial: -------------------------------------------------------------------------------- 1 | // Haz una función que cuente la cantidad de movimientos que se deben hacer para transformar la matriz en una matriz secuencial. 2 | 3 | function solution(arr) { 4 | let moves = 0 5 | for(let i = 1; i < arr.length; i++) { 6 | if(arr[i] <= arr[i-1]) { 7 | moves += arr[i-1] - arr[i] + 1 8 | arr[i] = arr[i-1] + 1 9 | } 10 | } 11 | return moves 12 | } 13 | 14 | const arr = [2, 1, 10, 1] 15 | solution(arr) // 12 -------------------------------------------------------------------------------- /intermedio/programacion-orientada-a-objetos/encuesta-de-dos-productos: -------------------------------------------------------------------------------- 1 | // Crea un programa que realice una encuesta a una persona la cual deberá completar la reseña de dos productos, almacenar cada reseña en el usuario correspondiente. 2 | 3 | class Entrevistado { 4 | constructor(nombre, localidad, reseñas = []) { 5 | this.nombre = nombre 6 | this.localidad = localidad 7 | this.reseñas = reseñas 8 | } 9 | 10 | realizarEncuesta(producto, reseña) { 11 | if(typeof producto !== "string" || typeof reseña !== "string") throw new Error("Ingrese un producto y una reseña válida") 12 | this.reseñas[producto] = reseña; 13 | } 14 | 15 | obtenerEncuestas() { 16 | let encuesta = `Encuesta de ${this.nombre}:\n` 17 | for(const producto in this.reseñas) { 18 | encuesta += `${producto}: ${this.reseñas[producto]}\n` 19 | } 20 | return encuesta; 21 | } 22 | } 23 | 24 | 25 | const martin = new Entrevistado("Martin", "CABA"); 26 | martin.realizarEncuesta("Mate", "Buena madera, aporta buen sabor"); 27 | martin.realizarEncuesta("Termo", "Mantiene la temperatura del agua"); 28 | martin.obtenerEncuestas(); -------------------------------------------------------------------------------- /intermedio/programacion-orientada-a-objetos/todo-app: -------------------------------------------------------------------------------- 1 | // Crear una aplicación todo-app (lista de tareas) 📝 2 | 3 | class Tarea { 4 | constructor(id, nombre) { 5 | this.id = id 6 | this.nombre = nombre; 7 | this.hecha = false 8 | } 9 | detalles() { 10 | console.log(`La tarea ${this.nombre} está ${this.hecha === false ? 'sin hacer' : 'hecha'}`) 11 | } 12 | finalizarTarea() { 13 | this.hecha = true 14 | } 15 | } 16 | 17 | class Lista { 18 | constructor(tareas = []){ 19 | this.tareas = tareas 20 | this.nextId = 1 21 | } 22 | agregarTarea(nombre) { 23 | if(typeof nombre !== 'string') throw new Error("error") 24 | const nuevaTarea = new Tarea(this.nextId++, nombre) 25 | this.tareas.push(nuevaTarea) 26 | } 27 | finalizarTarea(id) { 28 | const tarea = this.tareas.find(t => t.id === id) 29 | tarea.finalizarTarea() 30 | } 31 | removerTarea(id) { 32 | this.tareas = this.tareas.filter(t => t.id !== id) 33 | } 34 | mostrarTareas() { 35 | this.tareas.forEach((t) => t.detalles()) 36 | } 37 | } 38 | 39 | const list = new Lista() 40 | list.agregarTarea("Limpiar") 41 | list.agregarTarea("Jugar") 42 | list.removerTarea(1) 43 | list.finalizarTarea(2) 44 | list.mostrarTareas() -------------------------------------------------------------------------------- /intermedio/reemplazar-letra-siguiente: -------------------------------------------------------------------------------- 1 | // Haz una función que reemplace cada letra de un string por la siguiente letra según el abecedario inglés 2 | 3 | function solution(word) { 4 | const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] 5 | 6 | let newWord = [] 7 | for(let i = 0; i < word.length; i++) { 8 | if(alphabet.includes(word[i].toLowerCase())) { 9 | let position = alphabet.findIndex(e => e === word[i]) 10 | if(word[i].toLowerCase() === "z") { 11 | newWord.push(alphabet[0]) 12 | } else { 13 | newWord.push(alphabet[position + 1]) 14 | } 15 | } 16 | } 17 | return newWord.join("") 18 | } 19 | 20 | const word = 'crazy'; 21 | const word2 = 'codesignal' 22 | solution(word) // dsbaz 23 | solution(word2) // dpeftjhobm -------------------------------------------------------------------------------- /intermedio/rellenar-puertas-y-ventanas: -------------------------------------------------------------------------------- 1 | // Haz una función que rellene una matriz con puertas y ventanas donde la cantidad de puertas es par y las ventanas es impar, recibiendo un n° por parametros que indique la longitud de la matriz. 2 | 3 | function solution(quantity) { 4 | return Array(quantity).fill(null).map((value, index) => { 5 | if(index % 2 === 0) return "Puerta" 6 | return "Ventana" 7 | }) 8 | } 9 | 10 | solution(12) -------------------------------------------------------------------------------- /intermedio/saltar-obstaculos: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva encuentre la mínima cantidad de saltos que se deban dar para evadir los obstaculos dados. 2 | 3 | function solution(arr) { 4 | let jump = 1; 5 | for(let i = jump; ; jump++) { 6 | let canJump = true 7 | 8 | // Buscamos el NO multiplo 9 | for(let j = 0; j < arr.length; j++) { 10 | if(arr[j] % jump === 0) { 11 | canJump = false; 12 | break; 13 | } 14 | } 15 | 16 | if(canJump) { 17 | return jump 18 | } 19 | } 20 | } 21 | 22 | const inputArray = [5, 3, 6, 7, 9] // 4 23 | solution(inputArray) -------------------------------------------------------------------------------- /intermedio/subcadenas-con-longitudes: -------------------------------------------------------------------------------- 1 | // Dado un string dividir la cadena en el menor número posible de subcadenas separadas de carácteres idénticos y luego reemplazar con una concatenación su longitud con su respectiva letra. 2 | // ["aa", "bbb", "c"] 3 | // "aa" => 2a, "bbb" => 3b, "c" => c 4 | 5 | function solution(s) { 6 | let letter = ""; 7 | let word = ""; 8 | for(let i = 0; i < s.length; i++) { 9 | letter += s[i] 10 | if(s[i] !== s[i+1]) { 11 | if(letter.length > 1) { 12 | word += letter.length + letter[0] 13 | } else { 14 | word += letter 15 | } 16 | letter = "" 17 | } 18 | } 19 | return word; 20 | } 21 | 22 | solution("aabbbc") // 2a3bc -------------------------------------------------------------------------------- /intermedio/sumar-digitos-hasta-un-digito: -------------------------------------------------------------------------------- 1 | // Haz una función que dado un numero entero devuelva la cantidad de veces que se deben sumar dígitos hasta obtener un número de un solo dígito. 2 | 3 | function solution(n) { 4 | let count = 0; 5 | while(n >= 10) { 6 | n = n.toString().split("").reduce((acc, value) => acc + parseInt(value), 0) 7 | count++; 8 | } 9 | 10 | return count; 11 | } 12 | 13 | solution(5) // result = 0 14 | solution(100) // 1 + 0 + 0 = 1; result = 1; 15 | solution(91) // 9 + 1 = 10 => 1 + 0 = 1; result = 2; 16 | solution(877) // 8 + 7 + 7 = 22 => 2 + 2 = 4; result = 2; -------------------------------------------------------------------------------- /intermedio/sumar-digitos-recursiva: -------------------------------------------------------------------------------- 1 | // Haz una función recursiva que sume los dígitos ingresados 2 | 3 | function solution(n) { 4 | if(n < 10) return n // CASO BASE PARA DETENERSE (UN SOLO DIGITO) 5 | // Tomamos el último dígito de N usando n modulo de 10 y lo sumamos a la suma de digitos restantes 6 | return (n % 10) + solution(Math.floor(n / 10)) // '4' y '123' 7 | } 8 | 9 | solution(1234) // 10 10 | solution(987) // 24 11 | solution(3) // 3 -------------------------------------------------------------------------------- /intermedio/uber-costo-de-viaje: -------------------------------------------------------------------------------- 1 | // Uber esta construyendo una aplicación que estima cuanto costará tu viaje antes de pedirlo, eres un desarrollador que deberá obtener el resultado final a través del siguiente cálculo: 2 | // (costoPorMinuto * duracionViaje) + (costoPorMilla * distanciaViaje) 3 | 4 | function solution(duracionViaje, distanciaViaje, costoPorMinuto, costoPorMilla) { 5 | return costoPorMilla.map((_, index) => { 6 | return (costoPorMinuto[index] * duracionViaje) + (costoPorMilla[index] * distanciaViaje) 7 | }) 8 | } 9 | 10 | solution(30, 7, [0.2, 0.35, 0.4, 0.45], [1.1, 1.8, 2.3, 3.5]) // [13.7, 23.1, 28.1, 38] -------------------------------------------------------------------------------- /intermedio/uber-mejor-vehiculo: -------------------------------------------------------------------------------- 1 | // Resolver este ejercicio de Uber: siendo un nuevo usuario de Uber tienes $20 de tu primer viaje, quieres aprovecharlos en el mejor auto posible que puedas adquirir. Dado una cantidad de millas a recorrer y un costo por milla de cada auto calcular el mejor vehículo que puedes adquirir sin gastar dinero de tu bolsillo. 2 | 3 | function solution(miles, costPerMile) { 4 | const credit = 20; 5 | const rides = ["UberX", "UberXL", "UberPlus", "UberBlack", "UberSUV"] 6 | let result = "" 7 | for(let i = 0; i < costPerMile.length; i++) { 8 | if(costPerMile[i] * miles <= credit) { 9 | result = rides[i] 10 | if(i+1 === costPerMile.length) return result; 11 | } else { 12 | return result !== '' ? result : rides.at(-1); 13 | } 14 | } 15 | } 16 | 17 | const l = 30; 18 | const fares = [0.3, 0.5, 0.7, 1, 1.3] 19 | solution(l, fares) // UberXL 20 | 21 | solution(15, [0.7, 1, 1.3, 1.5, 1.7]) // Uber plus 22 | solution(19, [1, 2, 3, 4, 5]) // UberX 23 | 24 | function solution2(miles, costs) { 25 | const credit = 20; 26 | const rides = ["UberX", "UberXL", "UberPlus", "UberBlack", "UberSUV"] 27 | 28 | const index = costs.findIndex(cost => { 29 | return (cost * miles) > credit; 30 | }) 31 | return index > 0 ? rides[index - 1] : rides.at(-1); 32 | } 33 | 34 | solution2(30, [0.3, 0.5, 0.7, 1, 1.3]) // UberXL 35 | solution2(15, [0.7, 1, 1.3, 1.5, 1.7]) // Uber plus 36 | solution2(19, [1, 2, 3, 4, 5]) // UberX -------------------------------------------------------------------------------- /intermedio/validar-ipv4: -------------------------------------------------------------------------------- 1 | // Haz una función que devuelva True si la IP ingresada pertenece al protocolo Ipv4. 2 | 3 | function solution(ip) { 4 | const fragments = ip.split(".") 5 | let result = false 6 | for(let i = 0; i < fragments.length; i++){ 7 | if(fragments[i] === '' || !/^\d+$/.test(fragments[i])) return false 8 | if(fragments[i].length > 1 && fragments[i][0] === '0') return false 9 | 10 | const num = parseInt(fragments[i]) 11 | if(num >= 0 && num <= 255) { 12 | result = true 13 | } else { 14 | result = false 15 | break; 16 | } 17 | } 18 | return fragments.length === 4 ? result : false 19 | } 20 | 21 | const ipv4 = '172.16.254.1' 22 | solution(ipv4) // TRUE 23 | const ipv4dos = '64.233.161.00' 24 | solution(ipv4dos) // FALSE 25 | const ipv4tres = '124.52.67.1a' 26 | solution(ipv4tres) // FALSE -------------------------------------------------------------------------------- /teoria/funciones-y-tipos: -------------------------------------------------------------------------------- 1 | // Funciones y tipos de funciones 2 | 3 | // Declarativa 4 | function sumar(num1, num2) { 5 | return num1 + num2; 6 | } 7 | 8 | sumar(2, 10) 9 | 10 | // Constante con valor de función asignado 11 | const funcion = sumar(20,50) 12 | funcion // 70 13 | 14 | // Arrow Function 15 | const restar = (num1, num2) => { 16 | return num1 - num2; 17 | } 18 | 19 | restar(12, 6) 20 | 21 | // Recursivas 22 | const factorial = (num) => { 23 | if(num === 1 || num === 0) { 24 | return 1; 25 | } 26 | return num * factorial(num-1); 27 | } 28 | 29 | factorial(5) // 120 -------------------------------------------------------------------------------- /teoria/manejar-errores: -------------------------------------------------------------------------------- 1 | // ❗ Como manejar errores en Javascript correctamente 2 | 3 | // Error => Clase padre y CustomizedError es la clase hija 4 | // Super(message) llama al constructor padre (ERROR) con el mensaje de error proporcionado 5 | class CustomizedError extends Error { 6 | constructor(message, name = "Connection Error") { 7 | super(message) 8 | this.name = name 9 | } 10 | } 11 | 12 | function sumNums(a,b) { 13 | if((a+b) > 10) throw new CustomizedError("Something went wrong.." , "Bad Operation") 14 | return a + b; 15 | } 16 | 17 | function makeOperation() { 18 | try { 19 | const result = sumNums(15,2) 20 | return result 21 | } catch(error) { 22 | if(error instanceof CustomizedError) { 23 | console.error(`Error: ${error.name}, ${error.message}`) 24 | } else { 25 | console.error(`Unknown Error: ${error.message}`) 26 | } 27 | } 28 | } 29 | 30 | makeOperation() -------------------------------------------------------------------------------- /teoria/manejar-errores-sin-trycatch: -------------------------------------------------------------------------------- 1 | // Manejar errores sin usar try catch para mejorar la optimización del código. 2 | 3 | class MyError extends Error { 4 | constructor(message) { 5 | super(message) 6 | this.name = "Custom Error" 7 | } 8 | } 9 | 10 | function sumOne(num) { 11 | if(typeof num !== 'number') { 12 | return { 13 | result: null, 14 | error: new MyError("Parameter must be a number!") 15 | } 16 | } 17 | 18 | let output = num + 1; 19 | return { 20 | result: output, 21 | error: null 22 | } 23 | } 24 | 25 | function makeOperation() { 26 | const { result, error } = sumOne(10); 27 | if(error) { 28 | console.log(`Error ${error.name}: ${error.message}`) 29 | } else { 30 | return result; 31 | } 32 | } 33 | makeOperation() -------------------------------------------------------------------------------- /teoria/operadores: -------------------------------------------------------------------------------- 1 | // Operadores en Javascript 2 | 3 | let producto1 = "PARLANTE" 4 | let producto2 = "parlante" 5 | let num1 = 8 6 | let num2 = '8' 7 | let num3 = 4 8 | 9 | // == === 10 | if(num1 == num2) { // == <- Compara pero no estrictamente, === <- Compara estrictamente 11 | console.log("Son iguales pero no estrictamente iguales") 12 | } else { 13 | console.log("No son iguales") 14 | } 15 | 16 | // !== <- Distinto de 17 | if(producto1 !== producto2) console.log("Son distintos") 18 | 19 | // > y < 20 | if(num1 > num3) console.log(`${num1} es mayor que ${num3}`) 21 | 22 | // >= y <= 23 | if(num3 <= num1) console.log(`${num1} es menor o igual que ${num3}`) 24 | 25 | // && <-- (solo si) Ambas condiciones son verdaderas 26 | if(typeof num1 === "number" && typeof num3 === "number") console.log("Ambos son numeros") 27 | 28 | // || <-- Una de las dos condiciones debe ser verdadera 29 | if(typeof num1 === "number" || typeof num2 === "number") console.log("Uno de los dos es un número") 30 | 31 | // ?? <-- Fusión de nulos, si el primer valor es undefined o null se le asignará el segundo valor 32 | const letter = undefined ?? 'a' 33 | const num = null ?? 5 34 | console.log(letter, num) -------------------------------------------------------------------------------- /teoria/que-es-un-lenguaje-dinamico: -------------------------------------------------------------------------------- 1 | // ¿Qué quiere decir que un lenguaje de programación sea DINÁMICO? 2 | let word = "Hola mundo"; 3 | typeof word // 'string' 4 | 5 | word = 10; 6 | typeof word; // 'number' -------------------------------------------------------------------------------- /teoria/variable-y-tipos: -------------------------------------------------------------------------------- 1 | // Variables y tipos de variables en Javascript 2 | 3 | // Variable => Es un contenedor donde se pueden almacenar valores y cualquier tipo de dato 4 | 5 | var mate; 6 | mate = "Cerámica artesanal"; 7 | 8 | var mate; 9 | mate = "Plástico"; // Estamos reedeclarando la variable MATE 10 | 11 | let cantidadDeMates; 12 | cantidadDeMates = 5; 13 | cantidadDeMates = 10; // Estamos reasignando el valor de cantidadDeMates 14 | 15 | // const descripcion; <-- ¡MAL! Debe declararse con un valor 16 | const descripcion = "Infusión a base de hojas de yerba" // No se depuede reedeclarar y ni reasignar el valor 17 | --------------------------------------------------------------------------------