Solución… 😄
.
Por fin se logró... 😅.
.
Para la realización del reto es importante convertir fechas en String a objetos de fecha Date. Puede realizarse de la siguiente manera:
.
// donde 'date' es un string en formato dd/mmnewDate(`${date}${newDate().getFullYear()}`)
.
Cuando queremos saber si una habitación no es disponible, debemos recorrer toda la lista de reservas 'reserva actual' y comparar los checkIn y checkOut de estas con los de la reserva que queremos realizar 'reserva'.
.
Las condiciones son las siguientes:
.
.
Por lo que si alguna de estas se cumple, debemos verificar si el número de la habitación corresponde al de la reserva que queremos realizar. Si cumple significa que la habitación no es disponible, caso contrario al no cumplirse ninguna de las primeras 3 condiciones, la habitación es disponible.
.
Código:
.
exportfunctionhotelSystem(rooms){let roomList =[];// Buscar reserva por idfunctionsearchReservation(id){let foundRoom = roomList.find((room)=> room.id=== id);if(foundRoom){return foundRoom;}thrownewError("La reservación no fue encontrada");}// Ordenar reservasfunctiongetSortReservations(){let sortedRooms =[...roomList].sort((a, b)=>{let dateA =convertToDate(a.checkIn);let dateB =convertToDate(b.checkIn);return dateA - dateB;});return sortedRooms;}// Convertir a fechasfunctionconvertToDate(date){returnnewDate(`${date}${newDate().getFullYear()}`);}// Agregar reservafunctionaddReservation(reservation){if(!isAvailable(reservation)){thrownewError("La habitación no está disponible");} roomList.push(reservation);return'Reserva exitosa';}// Verificar si la habitación está disponiblefunctionisAvailable(reservation){let resIn = reservation.checkIn;let resOut = reservation.checkOut;for(let actRes of roomList){let actCheckIn = actRes.checkIn;let actCheckOut = actRes.checkIn;if((resIn >= actCheckIn && resIn < actCheckOut)||(resOut > actCheckIn && resOut <= actCheckOut)||(resIn <= actCheckIn && resOut >= actCheckOut)){if(actRes.roomNumber=== reservation.roomNumber){returnfalse;}}}returntrue;}// Remover reserva por idfunctionremoveReservation(id){let index = roomList.findIndex((room)=> room.id=== id);if(index >-1){return roomList.splice(index,1)[0];}else{thrownewError("La reservación que se busca remover no existe");}}// Retornamos todas las reservasfunctiongetReservations(){return roomList;}// Retornar las habitaciones disponiblesfunctiongetAvailableRooms(checkIn, checkOut){let availableRooms =[];for(let i =1; i <= rooms; i++){let reservation ={ checkIn, checkOut,roomNumber: i };if(isAvailable(reservation)){ availableRooms.push(i);}}return availableRooms;}return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms
};}
Saludos.
Tengo una pregunta ¿A alguien mas le pasa que no pueden seguir avanzando mas en desafío?
Muchas gracias!!
hola, estoy igual, a partir de este punto no me deja avanzar.
!placeholder
exportfunctionhotelSystem(rooms){let reservations =[]const _rooms =newArray(rooms)for(let i =0; i < _rooms.length; i++) _rooms[i]= i +1constdateToNumber=(date)=>{const currentYear =newDate().getFullYear().toString()returnnewDate(date +'/'+ currentYear).getTime()}constoccupiedRooms=(checkIn,checkOut)=> reservations.filter(r=>dateToNumber(checkOut)>dateToNumber(r.checkIn)||dateToNumber(checkIn)<dateToNumber(r.checkOut)).map(r=> r.roomNumber)// Tu código aquíreturn{searchReservation(id){const reservation = reservations.find(r=> r.id=== id)if(!reservation)thrownewError("La reservación no fue encontrada")return reservation
},getSortReservations(){return[...reservations].sort((a, b)=>dateToNumber(a.checkIn)-dateToNumber(b.checkIn))},addReservation(reservation){const roomAvailable =!occupiedRooms(reservation.checkIn, reservation.checkOut).includes(reservation.roomNumber)if(!roomAvailable)thrownewError("La habitación no está disponible") reservations.push(reservation)return"La habitación se creo correctamente"},removeReservation(id){const reservation =this.searchReservation(id) reservations = reservations.filter(r=> r.id!== id)return reservation
},getReservations(){return reservations
},getAvailableRooms(checkIn, checkOut){return _rooms.filter(room=>!(occupiedRooms(checkIn,checkOut).includes(room)))}}}
Probablemente a alguien más le sirva, esto me ayudó a entender un poco cómo organizar las fechas.
Los números del 1 al 30 simulan un mes
Los números rojos (5 al 20) simulan una reserva vieja
Los números verdes simulan una nueva reserva
Como ven, hay 4 casos posibles para la nueva reserva.
Se puede encontrar complétamente dentro de la reserva vieja (Grafico 1)
Puede estar parcialmente dentro de la vieja reserva (Graficos 2 y 3)
Puede encontrarse fuera de la vieja reserva (Grafico 4)
La vieja reserva puede encontrarse completamente dentro de la nueva reserva
Todos estos casos tenemos que tenerlos en cuenta a la hora de chequear la disponibilidad de una habitación
!Foto
++MI SOLUCION++ 💪
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
exportfunctionhotelSystem(rooms){const reserv =[];return{searchReservation:id=>{const res = reserv.find(reserve=> reserve.id=== id);if(res)return res;elsethrownewError("La reservación no fue encontrada");},getSortReservations:()=>{return[...reserv].sort((reserve1, reserve2)=>{if(reserve1.checkIn> reserve2.checkIn)return1;if(reserve1.checkIn< reserve2.checkIn)return-1;if(reserve1.checkIn=== reserve2.checkIn)return0;});},addReservation:reservation=>{if(reservation.checkIn> reservation.checkOut){thrownewError("La fecha de llegada no puede ser después de la salida");}const isRoomReserved = reserv.filter(reserve=> reserve.checkIn<= reservation.checkOut&& reserve.checkOut>= reservation.checkIn).some(reserve=> reserve.roomNumber=== reservation.roomNumber);if(isRoomReserved)thrownewError("La habitación no está disponible"); reserv.push(reservation);return"Reservación registrada exitosamente";},removeReservation:id=>{const index = reserv.findIndex(reserve=> reserve.id=== id);if(index ===-1)thrownewError("La reservación que se busca remover no existe");return reserv.splice(index,1)[0];},getReservations:()=> reserv,getAvailableRooms:(checkIn, checkOut)=>{const availableRooms =[];let index =0;for(let i =0; i < rooms; i++){ availableRooms[i]= i +1;} reserv.filter(reserve=> reserve.checkIn<= checkOut && reserve.checkOut>= checkIn
).forEach(reserve=>{ index = availableRooms.findIndex(num=> reserve.roomNumber=== num);if(index !=-1) availableRooms.splice(index,1);});return availableRooms;}}}
Por lo que veo en su mayoría, todos coincidimos en el mismo error al momento de presentar este reto. La verdad estuvo super interesante porque aplicamos muchos conocimientos que hemos visto durante el curso.
Sin embargo, insisto que de tener una mejor documentación en los ejercicios nos ayudaria ahorrar algo de tiempo.
Creo que todos los que han presentado su Challenge saben de que estoy hablando.... algo falto documentar.. en fin fue un reto, pude hacerlo luego de unas horas quemando neuronas 🤣
Anti Spoiler Alert !!!!
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
exportfunctionhotelSystem(rooms){let reservations =[];functiondateToNumber(dateString){returnparseInt(dateString.split("/").reverse().join(""));}functiongetBookedRooms(checkIn, checkOut, roomNumber){const checkInInt =dateToNumber(checkIn);const checkOutInt =dateToNumber(checkOut);return reservations.find(res=>{const resCheckIn =dateToNumber(res.checkIn);const resCheckOut =dateToNumber(res.checkOut);return res.roomNumber== roomNumber &&((resCheckIn <= checkInInt && checkInInt <= resCheckOut)||(resCheckOut <= checkOutInt && checkOutInt <= resCheckOut))})}return{searchReservation:id=>{const result = reservations.find(reservation=> reservation.id== id);if(result){return result;}else{thrownewError("La reservación no fue encontrada.")}},getSortReservations:()=>{return reservations.sort((a, b)=>dateToNumber(a.checkIn)-dateToNumber(b.checkIn));},addReservation:({ id, name, checkIn, checkOut, roomNumber })=>{if(getBookedRooms(checkIn, checkOut, roomNumber)){thrownewError("La habitación no está disponible");}if(roomNumber > rooms){return"La habitación no existe.";}if(reservations.find(res=> res.id=== id)){return"Ya existe una habitacion con el id: "+ id;} reservations.push({ id, name, checkIn, checkOut, roomNumber
})return"La habitación fue reservada con éxito.";},removeReservation:id=>{const index = reservations.findIndex(res=> res.id=== id);if(index >=0){return reservations.splice(index,1)[0];}else{thrownewError("No existe una habitacion con el id: "+ id);}},getReservations:()=>{return reservations;},getAvailableRooms:(checkIn, checkOut)=>{const availableRooms =[];for(let i =1; i <= rooms; i++){if(!getBookedRooms(checkIn, checkOut, i)){ availableRooms.push(i);}}return availableRooms;}}}
Hola, Comparto mi solución;
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
💚
exportfunctionhotelSystem(rooms){const reservations =[];constsearchReservation=(id)=>{const reservation = reservations.find((room)=> room.id=== id);if(reservation ===undefined){thrownewError("La reservación no fue encontrada");}return reservation;};constgetSortReservations=()=>{const reservationsSorted =[...reservations]; reservationsSorted.sort((roomA, roomB)=>{return roomA.checkIn.localeCompare(roomB.checkIn,"en",{numeric:true,});});return reservationsSorted;};constaddReservation=(reservation)=>{ reservations.forEach((room)=>{if(room.roomNumber=== reservation.roomNumber){if( room.checkIn=== reservation.checkIn|| room.checkOut=== reservation.checkOut){thrownewError("La habitación no está disponible");}}}); reservations.push(reservation);return"La habitación se reservo correctamente";};constremoveReservation=(id)=>{const reservationIndex = reservations.findIndex((room)=> room.id=== id);if(reservationIndex <0){thrownewError("La reservación que se busca remover no existe");}const reservationRemoved = reservations[reservationIndex]; reservations.splice(reservationIndex,1);return reservationRemoved;};functionisAvailable(reservation){const checkIn = reservation.checkIn;const checkOut = reservation.checkOut;for(const currentReservation of reservations){const currentCheckIn = currentReservation.checkIn;const currentCheckOut = currentReservation.checkOut;if((checkIn >= currentCheckIn && checkIn < currentCheckOut)||(checkOut > currentCheckIn && checkOut <= currentCheckOut)||(checkIn <= currentCheckIn && checkOut >= currentCheckOut)){if(currentReservation.roomNumber=== reservation.roomNumber){returnfalse;}}}returntrue;}constgetReservations=()=> reservations;constgetAvailableRooms=(checkIn, checkOut)=>{const availableRooms =[];for(let i =1; i <= rooms; i++){const reservation ={ checkIn, checkOut,roomNumber: i };if(isAvailable(reservation)){ availableRooms.push(i);}}return availableRooms;};return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms,};}
exportfunctionhotelSystem(rooms){let reservations =[];functionsearchReservation(id){if(reservations.length>0){const result = reservations.find(r=> r.id=== id);if(result){return result;}else{thrownewError("La reservación no fue encontrada");}}else{thrownewError("No tiene reservaciones");}}functiongetSortReservations(){const copy =[...reservations]; copy.sort((a, b)=>{let dateA =newDate(a.checkIn);let dateB =newDate(b.checkIn);return dateA - dateB;})return copy;}functionaddReservation(reservation){let resIn =newDate(reservation.checkIn);let resOut =newDate(reservation.checkOut);let roomUse =[]; reservations.forEach(r=>{let dateIn =newDate(r.checkIn);let datekOut =newDate(r.checkOut);if(reservation.roomNumber=== r.roomNumber){if(((resIn >= dateIn)&&(resOut <= datekOut))||(resIn < datekOut)&&(resOut > dateIn)){ roomUse.push(r.roomNumber);}}});if(roomUse.includes(reservation.roomNumber)){thrownewError("La habitación no está disponible");} reservations.push(reservation)return"registro exitoso";}functionremoveReservation(id){let result = reservations.findIndex(r=> r.id=== id);if(result !==-1){return reservations.splice(result,1)[0];}else{thrownewError("La reservación que se busca remover no existe");}}functiongetReservations(){return reservations;}functiongetAvailableRooms(checkIn, checkOut){let freeRooms =[];let resIn =newDate(checkIn);let resOut =newDate(checkOut);for(let i =1; i <= rooms; i++){const room = reservations.find(element=> element.roomNumber=== i);if(room !==undefined){let dateIn =newDate(room.checkIn);let datekOut =newDate(room.checkOut);const inUse =((resIn >= dateIn)&&(resOut <= datekOut))||((resIn < datekOut)&&(resOut > dateIn));if(!inUse){ freeRooms.push(i);}}else{ freeRooms.push(i);}}console.log(freeRooms)return freeRooms;}return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms
};}
Saludos.
Alguien me podria ayudar?
Solo me falta pasar la ultima prueba :
functionhotelSystem(rooms){const reservations =[];functionsearchReservation(id){const index = reservations.findIndex((room)=> room.id=== id);if(index >-1){return reservations[index];}thrownewError("La reservación no existe");}functiongetSortReservations(){const copy =[...reservations]; copy.sort((a, b)=>{const aDate =newDate(`${a.checkIn}${newDate().getFullYear()}`);const bDate =newDate(`${b.checkIn}${newDate().getFullYear()}`);return aDate - bDate;});return copy;}functionaddReservation(reservation){if(!isAvailable(reservation)){thrownewError("La habitación se encuentra ocupada");} reservations.push(reservation);return`La reservación de ${reservation.name} fue agendada exitosamente`;}functionremoveReservation(id){const index = reservations.findIndex((room)=> room.id=== id);if(index >-1){const removedReservation = reservations[index]; reservations.splice(index,1);return removedReservation;}thrownewError("La habitación que se busca remover no existe");}functiongetReservations(){return reservations;}functionisAvailable(reservation){const checkIn = reservation.checkIn;const checkOut = reservation.checkOut;for(const currentReservation of reservations){const currentCheckIn = currentReservation.checkIn;const currentCheckOut = currentReservation.checkOut;if((checkIn >= currentCheckIn && checkIn < currentCheckOut)||(checkOut > currentCheckIn && checkOut <= currentCheckOut)||(checkIn <= currentCheckIn && checkOut >= currentCheckOut)){if(currentReservation.roomNumber=== reservation.roomNumber){returnfalse;}}}returntrue;}functiongetAvailableRooms(checkIn, checkOut){const availableRooms =[];for(let i =1; i <= rooms; i++){const reservation ={ checkIn, checkOut,roomNumber: i };if(isAvailable(reservation)){ availableRooms.push(i);}}return availableRooms;}return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms,};}
A continuación, mi solución:
exportfunctionhotelSystem(rooms){let numCuartos = rooms;let reservaciones =newArray();return{searchReservation(id){let result = reservaciones.find(reserv=> reserv.id== id);if(result ==undefined){thrownewError("La reservación no fue encontrada");}else{return result;}},getSortReservations(){let copiaReserv = reservaciones; copiaReserv.sort(function(a, b){let ac =newDate(a.checkIn);let bc =newDate(b.checkIn);if(ac < bc){return-1;}elseif(ac > bc){return1;}else{return0;}})return copiaReserv;},addReservation(reservation){let comprueba = reservaciones.every(function(item){if(item.roomNumber== reservation.roomNumber){let reservIn =newDate(reservation.checkIn);let reservOut =newDate(reservation.checkOut);let itemIn =newDate(item.checkIn);let itemOut =newDate(item.checkOut);//throw new Error(reservIn+reservOut+itemIn+itemOut)if(reservIn > itemOut || reservOut < itemIn){returntrue;}else{returnfalse;}}else{returntrue;}});if(comprueba){ reservaciones.push(reservation);return"";}else{thrownewError("La habitación no está disponible")}},removeReservation(id){if(reservaciones.findIndex((re)=> re.id== id)==-1){thrownewError("La reservación que se busca remover no existe");}else{let indice = reservaciones.findIndex((re)=> re.id== id);let reserva = reservaciones.find((re)=> re.id== id); reservaciones.splice(indice,1);return reserva;}},getReservations(){return reservaciones;},getAvailableRooms(chkIn, chkOut){let chIn = chkIn.split("/"); chIn.reverse(); chIn = chIn.join("/");let chOut = chkOut.split("/"); chOut.reverse(); chOut = chOut.join("/");let ocupadas = reservaciones.filter(function(item){if(newDate(item.checkOut)<newDate(chIn)||newDate(item.checkIn)>newDate(chOut)){returnfalse;}else{returntrue;}});let habOcu =newArray(); ocupadas.forEach(function(item){ habOcu.push(item.roomNumber);})let resultado =newArray();for(let i =1; i <= rooms; i++){let comprueba = habOcu.includes(i);if(!comprueba){ resultado.push(i);}}return resultado;}}}
Gracias al aporte de todos ustedes y en especial Harold lo logre.
exportfunctionhotelSystem(rooms){let reservas =[]functionsearchReservation(id){let buscado = reservas.find(x=> x.id== id)if(!buscado)thrownewError("La reservación no fue encontrad")elsereturn buscado
}functionstringToDate(str){// Expected format "dd/mm"const[day, month]= str.split("/");const year =newDate().getFullYear();const date =Date.parse(`${month}/${day}/${year}`);return date;}functiongetSortReservations(){//fecha de check-in de manera ascendente.let copiareservas =[...reservas].sort((a, b)=>{let fa =stringToDate(a.checkIn);let fb =stringToDate(b.checkIn);return fa - fb
})return copiareservas
}functionaddReservation(reservation){//disponible para las fechas de check-in y check-out. Si esta reservada -> un error "La habitación no está disponible".if(!isAvailable(reservation)){thrownewError("La habitación no está disponible");} reservas.push(reservation)return"Se ha reservado correctamente!!"}functionremoveReservation(id){//la retornará. si no exista -> error .let buscado = reservas.find(x=> x.id=== id)if(buscado){ reservas = reservas.filter(x=> x.id!== id)return buscado
}elsethrownewError("La reservación que se busca remover no existe");}functiongetReservations(){//todas las reservaciones.return reservas
}functionisAvailable(reserva){let resIn = reserva.checkIn;let resOut = reserva.checkOut;for(let actRes of reservas){let actCheckIn = actRes.checkIn;let actCheckOut = actRes.checkIn;if((resIn >= actCheckIn && resIn < actCheckOut)||(resOut > actCheckIn && resOut <= actCheckOut)||(resIn <= actCheckIn && resOut >= actCheckOut)){if(actRes.roomNumber=== reserva.roomNumber){returnfalse;}}}returntrue;}functiongetAvailableRooms(checkIn, checkOut){let disponibles =[]for(let i =1; i <= rooms; i++){let reservab ={checkIn: checkIn,checkOut: checkOut,roomNumber: i }if(isAvailable(reservab)) disponibles.push(i)}return disponibles
}return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms
}}
🛡️🛡️Escudo anti-spoilers🛡️🛡️
Mi solución al reto, usando class:
classHotel{ rooms =0 reservations =[];constructor(rooms){this.rooms= rooms;}searchReservation(id){let found =this.reservations.find((r)=> r.id=== id);if(!found)thrownewError('La reservación no fue encontrada"');return found;}getSortReservations(){return[...this.reservations].sort((a, b)=> a.checkIn> b.checkIn);}isValidReservation(newR, currentR){if((newR.checkIn< currentR.checkIn)&&(newR.checkOut< currentR.checkIn)||(newR.checkIn> currentR.checkOut)&&(newR.checkOut> currentR.checkOut)){returntrue;}returnfalse;}addReservation(newReservation){for(let currentReservation ofthis.reservations){if(newReservation.roomNumber=== currentReservation.roomNumber&&!this.isValidReservation(newReservation, currentReservation
)){thrownewError('"La habitación no está disponible".');}}this.reservations.push(newReservation);return"Reservacion realizada con éxito";}removeReservation(id){let index =this.reservations.findIndex((r)=> r.id=== id);if(index <0)thrownewError("La reservación que se busca remover no existe");returnthis.reservations.splice(index,1)[0];}getReservations(){returnthis.reservations;}getAvailableRooms(checkIn, checkOut){let availableRooms =[];for(let num =1; num <=this.rooms; num++){let notAvailable =this.reservations.filter((r)=> r.roomNumber=== num).some((r)=>{return!this.isValidReservation({ checkIn, checkOut }, r)})if(!notAvailable) availableRooms.push(num)}return availableRooms;}}exportconsthotelSystem=(rooms)=>newHotel(rooms)
me impresionan las soluciones de la comunidad,
uno aprende con personas que saben
Solucion
functionhotelSystem(rooms){// Creation of the hotel empty roomsconst reservations =newArray(rooms);for(let i =0; i < reservations.length; i++){ reservations[i]={roomNumber: i +1};}// Helper functionsfunctionstringToDate(str){// Expected format "dd/mm"const[day, month]= str.split("/");const year =newDate().getFullYear();const date =Date.parse(`${month}/${day}/${year}`);return date;}// Function to compare 2 date ranges and check for intersection between rangesfunctiondateRangeIntersect(range1Start, range1End, range2Start, range2End){return range1Start <= range2End && range1End >= range2Start;}functionsearchReservation(id){try{const reservation = reservations.find((reservation)=> reservation.id=== id
);console.log(reservation);return reservation;}catch(error){thrownewError(`Error, the reservation number: ${id} was not found!`);}}functiongetSortReservations(){const reservedRooms = reservations
.filter((room)=> room.hasOwnProperty("checkIn")).sort((roomA, roomB)=>{returnstringToDate(roomA.checkIn)-stringToDate(roomB.checkIn);});console.log("Currently reserved rooms: ", reservedRooms);return reservedRooms;}functionaddReservation(reservation){// Reservation structure// {// id: 1,// name: "John Doe",// checkIn: "01/01",// checkOut: "02/01",// roomNumber: 1,// }const{ checkIn, checkOut, roomNumber }= reservation;// Get room dataconst hotelRoom = reservations.find((room)=> room.roomNumber=== roomNumber
);// Check if room has checkin, and checkout properties if not,// then reserve the roomif( hotelRoom.hasOwnProperty("checkIn")&& hotelRoom.hasOwnProperty("checkOut")){// Convert date string to dateconst reservationCheckIn =stringToDate(checkIn);const reservationCheckOut =stringToDate(checkOut);const hotelCheckIn =stringToDate(hotelRoom.checkIn);const hotelCheckOut =stringToDate(hotelRoom.checkOut);// If the room was reserved previously check if dates intersectif(dateRangeIntersect( reservationCheckIn, reservationCheckOut, hotelCheckIn, hotelCheckOut
)){const error =newError("Error: This room is not available during this date!");console.log(error.message);return error;}}const roomIndex = reservations.findIndex((room)=> room.roomNumber=== roomNumber
);// Overwrite array item with the new data reservations[roomIndex]= reservation;return reservations;}functionremoveReservation(id){// Get reservation dataconst reservationIndex = reservations.findIndex((reservation)=> reservation.id=== id
);const reservation = reservations[reservationIndex];// Revert to default object reservations[reservationIndex]={roomNumber: reservation.roomNumber};console.log(`Your reservation for ${reservation.name} has been cancelled`);return reservation;}functiongetReservations(){console.log(reservations);return reservations;}functiongetAvailableRooms(checkIn, checkOut){// Convert reservation date string to date object checkIn =stringToDate(checkIn); checkOut =stringToDate(checkOut);// Filter rooms that are available using date object dataconst availableRooms = reservations.filter((room)=>{// Check for props checkIn and checkOutif(room.hasOwnProperty("checkIn")&& room.hasOwnProperty("checkOut")){// then compare both date ranges and return only free roomsconst roomCheckIn =stringToDate(room.checkIn);const roomCheckOut =stringToDate(room.checkOut);return!dateRangeIntersect( checkIn, checkOut, roomCheckIn, roomCheckOut
);}return room;}); availableRooms.forEach((room)=>console.log(`Room Available: ${room.roomNumber}`));return availableRooms;}return{ searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms,};}
My solution
.
.
.
.
exportfunctionhotelSystem(rooms){const reservations =[]return{searchReservation:(id)=>{const res = reservations.find((r)=> r.id=== id)if(!res)throwError("La reservación no fue encontrada")elsereturn res
},getSortReservations:()=>{return[...reservations].sort((a, b)=>getDate(a.checkIn)-getDate(b.checkIn))},addReservation:(reservation)=>{const isPosible = reservations.some((res)=>{if(res.roomNumber=== reservation.roomNumber){if(!isPosibleDate(reservation, res))returnfalse}returntrue})if(isPosible || reservations.length===0){ reservations.push(reservation)return''}else{throwError("La habitación no está disponible")}},removeReservation:(id)=>{const idx = reservations.findIndex((res)=> res.id=== id)if(idx >-1){return reservations.splice(idx,1)[0]}else{throwError("La reservación que se busca remover no existe")}},getReservations:()=> reservations,getAvailableRooms:(checkIn, checkOut)=>{const allRooms =newArray(rooms).fill(0).map((_, idx)=> idx +1)if(reservations.length===0){return allRooms
}const ocupateRes = reservations
.filter((res)=>!isPosibleDate(res,{ checkIn, checkOut
})).map(({ roomNumber })=> roomNumber)return allRooms
.filter((room)=>!ocupateRes.includes(room))}}}functionisPosibleDate(reservation, newReservation){const barCheckIn =getDate(reservation.checkIn)const barCheckOut =getDate(reservation.checkIn)const newCheckIn =getDate(newReservation.checkIn)const newCheckOut =getDate(newReservation.checkIn)return(barCheckIn > newCheckIn && barCheckOut <= newCheckIn)||(barCheckIn >= newCheckOut && barCheckOut < newCheckOut)}functiongetDate(date){const foo = date.split('/')returnnewDate(...[foo[1],foo[0]])}
Esta es mi solución
functionhotelSystem(rooms){const reservations =[];return{searchReservation:(id)=>{const reservation = reservations.find(element=> element.id=== id);if(reservation){return reservation;}else{thrownewError('La reservación no fue encontrada');}},getSortReservations:()=>{const sortedReservations = reservations.sort((a,b)=>{if(a.checkIn> b.checkIn){return1}if(a.checkIn< b.checkIn){return-1}if(b.checkIn=== a.checkIn){return0}})return sortedReservations;},addReservation:(reservation)=>{const noAvailableroom = reservations.some(element=> element.roomNumber=== reservation.roomNumber&&(element.checkIn<= reservation.checkIn|| element.checkOut>= reservation.checkOut))if(!noAvailableroom){ reservations.push(reservation)return'La habitación ha sido reservada'}else{thrownewError('La habitación no está disponible');}},removeReservation:(id)=>{const idReservation = reservations.findIndex(element=> element.id=== id);const reservation = reservations.at(idReservation)if(idReservation !==-1){ reservations.splice(idReservation,1);return reservation;}else{thrownewError('"La reservación que se busca remover no existe"');}},getReservations:()=>{return reservations;},getAvailableRooms:(checkIn, checkOut)=>{const availableRooms =[];for(let index =1; index <= rooms; index++){const noAvailableroom = reservations.some(element=> element.roomNumber=== index &&(element.checkIn<= checkIn || element.checkOut>= checkOut))if(!noAvailableroom){ availableRooms.push(index)}}return availableRooms;}}}