-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
52 changed files
with
857 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
{ | ||
"files.exclude": { | ||
"**/.git": true, | ||
"**/.svn": true, | ||
"**/.hg": true, | ||
"**/CVS": true, | ||
"**/.DS_Store": true, | ||
"**/Thumbs.db": true, | ||
"**/node_modules": true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
function checkJump(heights) { | ||
const maxValue = Math.max(...heights); | ||
const idxMaxValue = heights.indexOf(maxValue); | ||
const arraySplitted1 = heights.slice(0, idxMaxValue + 1); | ||
const arraySplitted2 = heights.slice(idxMaxValue, heights.length); | ||
const array1Increment = arraySplitted1.reduce((acc, curr, i, array) => array[i] >= array[i - 1]); | ||
const array2Decrement = arraySplitted2.reduce((acc, curr, i, array) => array[i] <= array[i - 1]); | ||
return array1Increment && array2Decrement; | ||
} | ||
|
||
const result = checkJump([1, 7, 3, 5]); | ||
console.log(result); | ||
|
||
module.exports = { checkJump }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
Crea un programa que compruebe que el trineo de Santa Claus hace una parabola al saltar entre ciudades. Recibes un array de números que representan la altura en la que se encuentra | ||
el trineo en cada momento. | ||
|
||
Para que la parabola sea correcta, el viaje del trineo debe ser ascendente al principio, llegar al punto más alto y descender hasta el final. No puede volver a subir una vez que ha | ||
bajado, ni puede iniciar el viaje bajando. Veamos unos ejemplos: | ||
|
||
const heights = [1, 3, 8, 5, 2] checkJump(heights) // true | ||
|
||
/\* Es `true`. El salto va de abajo a arriba y luego de arriba a abajo: | ||
|
||
8 (punto más alto) | ||
|
||
↗ ↘ 3 5 ↗ ↘ 1 2 \*/ | ||
|
||
const heights = [1, 7, 3, 5] checkJump(heights) // false | ||
|
||
/\* Es `false`. Va de abajo a arriba, de arriba a abajo y luego sube otra vez. | ||
|
||
7 5 ↗ ↘ ↗ 1 3 Necesitamos que el programa devuelva un boolean que indique si el trineo hace una parabola o no. | ||
|
||
A tener en cuenta Para que el salto sea válido tiene que subir una vez y bajar una vez. Si durante el salto se queda en la misma altura entre dos posiciones, la parabola continua. | ||
No hace falta que el punto de inicio y final sean el mismo (las ciudades pueden estar a diferentes alturas). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
const { checkJump } = require('./reto10'); // false | ||
|
||
test('reto10Test', () => { | ||
expect(checkJump([1, 3, 8, 5, 2])).toStrictEqual(true); | ||
expect(checkJump([1, 7, 3, 5])).toStrictEqual(false); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
// NO COMPLETADO | ||
|
||
function getCompleted(part, total) { | ||
return '1/1'; | ||
} | ||
|
||
module.exports = { getCompleted }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
Papa Noél está un poco preocupado porque los preparativos están llevando mucho tiempo. Hace poco se ha sacado una certificación de Scrum y ha decidido usar la metodología para | ||
organizar el trabajo de sus elfos. | ||
|
||
Le dicen la duración esperada de las tareas con un string con el formato hh:mm:ss y en el mismo formato cuánto tiempo llevan trabajando en ella. | ||
|
||
Pero Papa Noél no se entera rápidamente si falta o mucho para que termine, así que nos ha pedido que hagamos un programa que nos indique la porción de la tarea que ya se ha | ||
completado. | ||
|
||
Por ejemplo, si la tarea dura 03:00:00 y llevan trabajando 01:00:00 entonces ya han completado 1/3 de la tarea. En código: | ||
|
||
getCompleted('01:00:00', '03:00:00') // '1/3' getCompleted('02:00:00', '04:00:00') // '1/2' getCompleted('01:00:00', '01:00:00') // '1/1' getCompleted('00:10:00', '01:00:00') // | ||
'1/6' getCompleted('01:10:10', '03:30:30') // '1/3' getCompleted('03:30:30', '05:50:50') // '3/5 Ten en cuenta: | ||
|
||
El formato de la hora es hh:mm:ss. El formato de la salida es un string a/b donde a es la porción de la tarea que ya se ha completado y b es la porción de la tarea que falta por | ||
completar. La porción siempre se muestra con la menor fracción posible. (por ejemplo, nunca se mostraría 2/4 porque se puede representar como 1/2). Si ya se ha completado la tarea, | ||
la fracción sería 1/1. Ningun elfo ha sido maltratado durante la ejecución de este reto ni han tenido que usar Scrum de verdad. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const { getCompleted } = require('./reto11'); | ||
|
||
test('reto11Test', () => { | ||
expect(getCompleted('01:00:00', '03:00:00')).toStrictEqual('1/3'); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
function selectSleigh(distance, sleighs) { | ||
const items = sleighs | ||
.filter(item => item.consumption * distance <= 20) | ||
.map(item => { | ||
item.totalConsumption = item.consumption * distance; | ||
return item; | ||
}) | ||
.sort((a, b) => b.totalConsumption - a.totalConsumption); | ||
return items[0] ? items[0].name : null; | ||
} | ||
|
||
module.exports = { selectSleigh }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
Papa Noél tiene nuevos trineos eléctricos pero debe controlar el consumo eléctrico ya que sólo tiene una batería de 20W. | ||
|
||
Nos dan un array de trineos, de peor a mejor, con sus respectivos consumos. Cada trineo es un objeto con dos propiedades: name y consumption. | ||
|
||
El campo consumption es un número que representa la cantidad de vatios (W) que consume el trineo para cada unidad de distancia. El campo name es una cadena de texto que representa | ||
el nombre del trineo. | ||
|
||
Crea un programa que nos devuelva el nombre del mejor trineo disponible que nos permita cubrir la distancia. | ||
|
||
const distance = 30 const sleighs = [ { name: "Dasher", consumption: 0.3 }, { name: "Dancer", consumption: 0.5 }, { name: "Rudolph", consumption: 0.7 }, { name: "Midu", | ||
consumption: 1 } ] | ||
|
||
selectSleigh(distance, sleighs) // => "Dancer" | ||
|
||
// Dasher consume 9W para recorrer 30 de distancia // Dancer consume 15W para recorrer 30 de distancia // Rudolph consume 21W para recorrer 30 de distancia // Midu consume 30W para | ||
recorrer 30 de distancia | ||
|
||
// El mejor trineo con el que puede recorrer // la distancia es Dancer. | ||
|
||
// Dasher recorre la distancia pero es peor trineo // Rudolph y Midu no pueden recorrer la distancia con 20W. Recuerda que: | ||
|
||
La batería siempre es de 20W. La lista de trineos está ordenada de peor a mejor trineo. Tienes que devolver el nombre del mejor trineo que nos permita cubrir la distancia con los | ||
vatios que tenemos disponibles. Si ningún trineo es usable para la distancia, devuelve null. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
const { selectSleigh } = require('./reto12'); | ||
|
||
test('reto14Test', () => { | ||
expect( | ||
selectSleigh(1, [ | ||
{ name: 'pheralb', consumption: 0.3 }, | ||
{ name: 'TMChein', consumption: 0.5 }, | ||
]) | ||
).toStrictEqual('TMChein'); | ||
expect( | ||
selectSleigh(30, [ | ||
{ name: 'Dasher', consumption: 0.3 }, | ||
{ name: 'Dancer', consumption: 0.5 }, | ||
{ name: 'Rudolph', consumption: 0.7 }, | ||
{ name: 'Midu', consumption: 1 }, | ||
]) | ||
).toStrictEqual('Dancer'); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
function getFilesToBackup(lastBackup, changes) { | ||
return changes | ||
.filter(item => item[1] > lastBackup) | ||
.map(item => item[0]) | ||
.filter((value, index, array) => array.indexOf(value) === index) | ||
.sort((prev, next) => prev - next); | ||
} | ||
|
||
module.exports = { getFilesToBackup }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
Para evitar perder datos cuando el servidor se cae, Papa Noel ha decidido hacer backups incrementales. Un hacker llamado S4vitelf le esta ayudando. | ||
|
||
Por un lado, tenemos el timestamp de cuándo se hizo el último backup. | ||
|
||
También tenemos los cambios que se han realizado en un array de arrays. Cada array interno contiene dos elementos: el id del archivo modificado y el timestamp de la modificación. | ||
|
||
Tienes que crear un programa que devuelva un array con las id de los archivos que tendríamos que hacer backup porque han sido modificados desde el último backup y ordenados de | ||
forma ascendente. Ejemplo: | ||
|
||
const lastBackup = 1546300800 const changes = [ [ 3, 1546301100 ], [ 2, 1546300800 ], [ 1, 1546300800 ], [ 1, 1546300900 ], [ 1, 1546301000 ] ] | ||
|
||
getFilesToBackup(lastBackup, changes) // => [ 1, 3 ] // El archivo con id 1 ha sido modificado dos veces // después del último backup. | ||
|
||
// El archivo con id 2 no ha sido modificado después // del último backup. | ||
|
||
// El archivo con id 3 ha sido modificado una vez // después del último backup. | ||
|
||
// Tenemos que hacer una copia de seguridad // de los archivos 1 y 3. Recuerda que: | ||
|
||
Devuelve la id de los archivos que han sido modificados después del último backup. Devuelve un array vacío si no hay archivos que hacer backup. Recuerda que deben estar ordenados | ||
los id de forma ascendente. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
const { getFilesToBackup } = require('./reto13'); | ||
|
||
const lastBackup = 1546300800; | ||
const changes = [ | ||
[3, 1546301100], | ||
[2, 1546300800], | ||
[1, 1546300800], | ||
[1, 1546300900], | ||
[1, 1546301000], | ||
]; | ||
|
||
test('reto13Test', () => { | ||
expect(getFilesToBackup(lastBackup, changes)).toStrictEqual([1, 3]); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
function getOptimalPath(path) { | ||
const funcMinPath = (acc, curr) => | ||
curr.map((value, i) => { | ||
return value + Math.min(acc[i], acc[i + 1]); | ||
}); | ||
return path.reverse().reduce(funcMinPath)[0]; | ||
} | ||
|
||
module.exports = { getOptimalPath }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
Santa Claus está construyendo pirámides de hielo en el Polo Norte para entrenar a sus renos. | ||
|
||
Cada reno comienza en la cima de la pirámide y debe elegir el camino óptimo hacia abajo para recorrerlo en el menor tiempo posible. Cada nivel tiene un número que determina el | ||
tiempo que necesita para llegar ahí. | ||
|
||
Al llegar a una posición, el reno solo puede deslizarse hacia abajo y en diagonal hacia la izquierda o la derecha. Visualmente, la pirámide se ve así: | ||
|
||
0 | ||
|
||
/ \ | ||
7 4 / \ / \ | ||
2 4 6 En código la representamos así: | ||
|
||
[ [0], [7, 4], [2, 4, 6] ] Santa Claus necesita un programa que le dice cuál es el tiempo mínimo que puede tomar cada reno para deslizarse por la pirámide usando el camino más | ||
óptimo. | ||
|
||
En el ejemplo anterior, el camino más óptimo es 0 -> 4 -> 4, que toma un total de 0 + 4 + 4 = 8 unidades de tiempo. El resultado sería: 8. | ||
|
||
¿Por qué no es 6? No es 0 -> 4 -> 2 porque al bajar a la posición del 4 ya no puede diagonalmente llegar a la posición del 2. Así que el camino más corto posible es 8. Más | ||
ejemplos: | ||
|
||
getOptimalPath([[0], [2, 3]]) // 2 // 0 -> 2 | ||
|
||
getOptimalPath([[0], [3, 4], [9, 8, 1]]) // 5 // 0 -> 4 -> 1 | ||
|
||
getOptimalPath([[1], [1, 5], [7, 5, 8], [9, 4, 1, 3]]) // 8 // 1 -> 1 -> 5 -> 1 A tener en cuenta: | ||
|
||
Ten en cuenta que sólo puedes bajar en diagonal y hacia abajo desde cualquier posición. La primera posición de la pirámide puede ser diferente a 0. Las pirámides pueden tener hasta | ||
10 niveles. Los números en las pirámides pueden ser negativos. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
const { getOptimalPath } = require('./reto14'); | ||
|
||
test('reto14Test', () => { | ||
expect(getOptimalPath([[0], [2, 3]])).toStrictEqual(2); | ||
expect(getOptimalPath([[0], [3, 4], [9, 8, 1]])).toStrictEqual(5); | ||
expect(getOptimalPath([[1], [1, 5], [7, 5, 8], [9, 4, 1, 3]])).toStrictEqual(8); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
// CASI COMPLETADO | ||
|
||
function decorateTree(base) { | ||
const dict = { | ||
PB: 'R', | ||
BP: 'R', | ||
RP: 'B', | ||
PR: 'B', | ||
BR: 'P', | ||
RB: 'P', | ||
BB: 'B', | ||
PP: 'P', | ||
RR: 'R', | ||
}; | ||
|
||
const result = [base]; | ||
let currentRow = base.split(' '); | ||
const length = currentRow.length - 1; | ||
for (let i = 0; i < length; i++) { | ||
currentRow = [...currentRow].splice(1).map((curr, i) => { | ||
return dict[currentRow[i] + curr]; | ||
}); | ||
result.unshift(currentRow.join(' ')); | ||
} | ||
return result; | ||
} | ||
|
||
const result = decorateTree('B P R P'); | ||
console.log(result); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
Una pareja está poniendo el árbol de navidad. El chico es un motivado de los adornos navideños y quiere que quede perfectamente equilibrado. Tiene tres tipos de decoraciones: | ||
|
||
Bolas de colores : B Regalos pequeños : R Piñas de pino : P El árbol de navidad es un triángulo que hay que generar. Ya tienen la base montada, que sería la primera fila, y a | ||
partir de ahí tienen que ir colocando las decoraciones hacía arriba siguiendo una fórmula. | ||
|
||
Arriba coloca : P R B P Si abajo tiene : P P B P R P B R Las combinaciones también son al revés. Por ejemplo, si abajo es B P, arriba es R. Pero también será R si abajo es P B. | ||
También si abajo tienes dos veces la misma letra, arriba será la misma letra. Por ejemplo, si abajo es B B, arriba es B. | ||
|
||
Con estas reglas, podríamos ver el árbol que generaríamos con la base B P R P: | ||
|
||
R P B R B B B P R P Escribe un programa que reciba el string B P R P y devuelva un array con la representación del árbol. | ||
|
||
decorateTree('B P R P') // [ // 'R', // 'P B', // 'R B B', // 'B P R P' // ] | ||
|
||
decorateTree('B B') // ['B', 'B B'] Ten en cuenta que: | ||
|
||
El programa recibe siempre la cadena de texto que representa la base del árbol. Hay que generar el árbol completo, es decir, la base y las filas que se generan a partir de ella, | ||
hasta arriba. Hay que seguir la fórmula para saber qué decoración colocar en cada posición. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// decorateTree('B P R P'); | ||
// // [ | ||
// // 'R', | ||
// // 'P B', | ||
// // 'R B B', | ||
// // 'B P R P' | ||
// // ] | ||
|
||
// decorateTree('B B'); // ['B', 'B B'] | ||
|
||
test('reto15Test', () => { | ||
// expect(fixLetter(` hello, how are you?? do you know if santa claus exists? i really hope he does! bye `)).toStrictEqual( | ||
// 'Hello, how are you? Do you know if Santa Claus exists? I really hope he does! Bye.' | ||
// ); | ||
// expect(fixLetter(` Hi Santa claus. I'm a girl from Barcelona , Spain . please, send me a bike. Is it possible?`)).toStrictEqual( | ||
// `Hi Santa Claus. I'm a girl from Barcelona, Spain. Please, send me a bike. Is it possible?` | ||
// ); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
function fixLetter(letter) { | ||
return letter | ||
.trim() // Eliminar espacios al principio y final de la frase | ||
.replace(/[\?\!]{2,}/g, '?') // Eliminar multiples interrogaciones | ||
.replace(/,/g, ', ') // Separación en las comas | ||
.replace(/\s+/g, ' ') // Eliminar multiples separaciones | ||
.replace(/santa claus/gi, 'Santa Claus') // Mostar Santa Claus en mayuscula | ||
.replace(/\s+[\?\.\,]/g, text => text.trim()) // Eliminar el espacio antes de signos | ||
.replace(/[\?\!\.]+[\s][a-z]|^[a-z]/gi, char => char.toUpperCase()) // Mostrar la primera letra en mayuscula si hay signos de interrogacion, exclamacion o punto y un espacio | ||
.replace(/[a-z]$/gi, char => char + '.'); // Añadir un punto a final de frase | ||
} | ||
|
||
module.exports = { fixLetter }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
Papá Noel está empezando a recibir un montón de cartas pero tienen un montón de problemas de formato. Para mejorar la lectura, va a escribir un programa que, dado un texto, lo | ||
formatea de acuerdo a las siguientes reglas: | ||
|
||
Eliminar espacios al inicio y al final Eliminar múltiples espacios en blanco y dejar sólo uno Dejar un espacio después de cada coma Quitar espacios antes de coma o punto Las | ||
preguntas sólo deben terminar con un signo de interrogación La primera letra de cada oración debe estar en mayúscula Poner en mayúscula la palabra "Santa Claus" si aparece en la | ||
carta Poner un punto al final de la frase si no tiene puntuación Las cartas las escriben inglés y aquí tenemos un ejemplo: | ||
|
||
fixLetter(`hello, how are you?? do you know if santa claus exists? i really hope he does! bye `) // Hello, how are you? Do you know if Santa Claus exists? I really hope he does! | ||
Bye. | ||
|
||
fixLetter(" Hi Santa claus. I'm a girl from Barcelona , Spain . please, send me a bike. Is it possible?") // Hi Santa Claus. I'm a girl from Barcelona, Spain. Please, send me a | ||
bike. Is it possible? A tener en cuenta: | ||
|
||
No te tienes que preocupar por los signos de puntuación que no sean coma, punto o interrogación. Asegúrate de respetar los saltos de línea y espacios originales. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
const { fixLetter } = require('./reto16'); | ||
|
||
test('reto16Test', () => { | ||
expect(fixLetter(` hello, how are you?? do you know if santa claus exists? i really hope he does! bye `)).toStrictEqual( | ||
'Hello, how are you? Do you know if Santa Claus exists? I really hope he does! Bye.' | ||
); | ||
expect(fixLetter(` Hi Santa claus. I'm a girl from Barcelona , Spain . please, send me a bike. Is it possible?`)).toStrictEqual( | ||
`Hi Santa Claus. I'm a girl from Barcelona, Spain. Please, send me a bike. Is it possible?` | ||
); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
function carryGifts(gifts, maxWeight) { | ||
const bags = []; | ||
let currentBag = []; | ||
gifts.forEach(item => { | ||
if (item.length > maxWeight) return; | ||
const totalLength = currentBag.reduce((acc, curr) => acc + curr.length, 0) + item.length; | ||
if (totalLength > maxWeight) { | ||
bags.push(currentBag.join(' ')); | ||
currentBag = []; | ||
} | ||
currentBag.push(item); | ||
}); | ||
if (currentBag.length > 0) bags.push(currentBag.join(' ')); | ||
return bags; | ||
} | ||
|
||
module.exports = { carryGifts }; |
Oops, something went wrong.