Playground - Sistema de reservaciones de un hotel
Clase 50 de 99 • 30 días de JavaScript
Contenido del curso
Clase 50 de 99 • 30 días de JavaScript
Contenido del curso
Harold Zurita Simon
PEDRO MARTIN LOPEZ MILANI
JOHN FREDDY BUITRAGO QUEVEDO
David Higuera
Daniel Sebastián Rodríguez
JAIME EDUARDO DIAZ TOBON
Joan Alexander Valerio Rodríguez
Felipe Moreno
Angel Javier Sanchez Tenjo
Alexis Corrales
Orangel Brito
Osvaldo Martinez Guillen
Leonardo de los angeles Espinoza Hernandez
Rubén Hernández Hernández
Andrés Soret Chacin
Ramsés Alfonzo Salinas Mejías
Hiver Tapia
Alejandro Anaya
willmar fernando romero marin
Elias Rayas Gonzalez
Rafael Livise Larico
Jaime Alberto Parra Acevedo
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/mm new Date(`${date} ${new Date().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: .
export function hotelSystem(rooms) { let roomList = []; // Buscar reserva por id function searchReservation(id) { let foundRoom = roomList.find((room) => room.id === id); if (foundRoom) { return foundRoom; } throw new Error("La reservación no fue encontrada"); } // Ordenar reservas function getSortReservations() { let sortedRooms = [...roomList].sort((a, b) => { let dateA = convertToDate(a.checkIn); let dateB = convertToDate(b.checkIn); return dateA - dateB; }); return sortedRooms; } // Convertir a fechas function convertToDate(date) { return new Date(`${date} ${new Date().getFullYear()}`); } // Agregar reserva function addReservation(reservation) { if (!isAvailable(reservation)) { throw new Error("La habitación no está disponible"); } roomList.push(reservation); return 'Reserva exitosa'; } // Verificar si la habitación está disponible function isAvailable(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) { return false; } } } return true; } // Remover reserva por id function removeReservation(id) { let index = roomList.findIndex((room) => room.id === id); if (index > -1) { return roomList.splice(index, 1)[0]; } else { throw new Error("La reservación que se busca remover no existe"); } } // Retornamos todas las reservas function getReservations() { return roomList; } // Retornar las habitaciones disponibles function getAvailableRooms(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
export function hotelSystem(rooms) { let reservations = [] const _rooms = new Array(rooms) for (let i = 0; i < _rooms.length; i++) _rooms[i] = i + 1 const dateToNumber = (date) => { const currentYear = new Date().getFullYear().toString() return new Date(date + '/' + currentYear).getTime() } const occupiedRooms = (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) throw new Error("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) throw new Error("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.
!Foto
++MI SOLUCION++ 💪 . . . . . . . . . . . . . . . .
export function hotelSystem(rooms) { const reserv = []; return { searchReservation: id => { const res = reserv.find(reserve => reserve.id === id); if (res) return res; else throw new Error("La reservación no fue encontrada"); }, getSortReservations: () => { return [...reserv].sort((reserve1, reserve2) => { if (reserve1.checkIn > reserve2.checkIn) return 1; if (reserve1.checkIn < reserve2.checkIn) return -1; if (reserve1.checkIn === reserve2.checkIn) return 0; }); }, addReservation: reservation => { if (reservation.checkIn > reservation.checkOut) { throw new Error("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) throw new Error("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) throw new Error("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 !!!!
. . . . . . . . . . . . . . . . . . . . . .
export function hotelSystem(rooms) { let reservations = []; function dateToNumber(dateString) { return parseInt(dateString.split("/").reverse().join("")); } function getBookedRooms(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{ throw new Error("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)) { throw new Error("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 { throw new Error("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;
💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚 💚
export function hotelSystem(rooms) { const reservations = []; const searchReservation = (id) => { const reservation = reservations.find((room) => room.id === id); if (reservation === undefined) { throw new Error("La reservación no fue encontrada"); } return reservation; }; const getSortReservations = () => { const reservationsSorted = [...reservations]; reservationsSorted.sort((roomA, roomB) => { return roomA.checkIn.localeCompare(roomB.checkIn, "en", { numeric: true, }); }); return reservationsSorted; }; const addReservation = (reservation) => { reservations.forEach((room) => { if (room.roomNumber === reservation.roomNumber) { if ( room.checkIn === reservation.checkIn || room.checkOut === reservation.checkOut ) { throw new Error("La habitación no está disponible"); } } }); reservations.push(reservation); return "La habitación se reservo correctamente"; }; const removeReservation = (id) => { const reservationIndex = reservations.findIndex((room) => room.id === id); if (reservationIndex < 0) { throw new Error("La reservación que se busca remover no existe"); } const reservationRemoved = reservations[reservationIndex]; reservations.splice(reservationIndex, 1); return reservationRemoved; }; function isAvailable(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) { return false; } } } return true; } const getReservations = () => reservations; const getAvailableRooms = (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, }; }
export function hotelSystem(rooms) { let reservations = []; function searchReservation(id) { if (reservations.length > 0) { const result = reservations.find(r => r.id === id); if (result) { return result; } else { throw new Error("La reservación no fue encontrada"); } } else { throw new Error("No tiene reservaciones"); } } function getSortReservations() { const copy = [...reservations]; copy.sort((a, b) => { let dateA = new Date(a.checkIn); let dateB = new Date(b.checkIn); return dateA - dateB; }) return copy; } function addReservation(reservation) { let resIn = new Date(reservation.checkIn); let resOut = new Date(reservation.checkOut); let roomUse = []; reservations.forEach(r => { let dateIn = new Date(r.checkIn); let datekOut = new Date(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)) { throw new Error("La habitación no está disponible"); } reservations.push(reservation) return "registro exitoso"; } function removeReservation(id) { let result = reservations.findIndex(r => r.id === id); if (result !== -1) { return reservations.splice(result, 1)[0]; } else { throw new Error("La reservación que se busca remover no existe"); } } function getReservations() { return reservations; } function getAvailableRooms(checkIn, checkOut) { let freeRooms = []; let resIn = new Date(checkIn); let resOut = new Date(checkOut); for (let i = 1; i <= rooms; i++) { const room = reservations.find(element => element.roomNumber === i); if (room !== undefined) { let dateIn = new Date(room.checkIn); let datekOut = new Date(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 :
function hotelSystem(rooms) { // Tu código aquí let reservations = []; return { searchReservation: (id) => { const reservation = reservations.find(reservation => reservation.id === id); if (!reservation) { throw new Error("La reservación no fue encontrada"); } return reservation; }, getSortReservations: () => { return [...reservations].sort((a, b) => new Date(a.checkIn) - new Date(b.checkIn)); }, addReservation: (reservation) => { const { checkIn, checkOut, roomNumber } = reservation; const isRoomAvailable = reservations.every(reservation => { const { checkIn: checkInRes, checkOut: checkOutRes } = reservation; return checkIn < checkInRes && checkOut < checkInRes || checkIn > checkOutRes && checkOut > checkOutRes; }); if (!isRoomAvailable) { throw new Error("La habitación no está disponible"); } reservations.push(reservation); return "Reservación agregada exitosamente"; }, removeReservation: (id) => { const reservation = reservations.find(reservation => reservation.id === id); if (!reservation) { throw new Error("La reservación que se busca remover no existe"); } reservations = reservations.filter(reservation => reservation.id !== id); return reservation; }, getReservations: () => reservations, getAvailableRooms: (checkIn, checkOut) => { const availableRooms = []; [...Array(rooms)].forEach((_, index) => { const isRoomAvailable = reservations.every((reservation) => { if (reservation.roomNumber === index + 1) { const { checkIn: checkInRes, checkOut: checkOutRes } = reservation; return checkIn >= checkOutRes || checkOut <= checkInRes; } return true; }); if (isRoomAvailable) { availableRooms.push(index + 1); } }); return availableRooms; }, } }
Los dates de checkOut y checkIn que recibimos en los objetos estan en formato MM/DD?
Están en formato dd/mm :D
Mi solución 💚 💚 💚 💚 💚 💚
function hotelSystem(rooms) { const totalRooms = rooms; const reservations = []; const searchReservation = (id) => { const reservation = reservations.find((reservation) => reservation.id === id) if (reservation === undefined) throw new Error("La reservación no fue encontrada") return reservation } const getSortReservations = () => [...reservations].sort((resA, resB) => { const dateA = new Date(resA.checkIn) const dateB = new Date(resB.checkIn) return dateA - dateB }) const addReservation = (reservation) => { const newCheckIn = new Date(reservation.checkIn) const newCheckOut = new Date(reservation.checkOut) const isReserved = reservations.findIndex((res) => { const actualCheckIn = new Date(res.checkIn) const actualCheckOut = new Date(res.checkOut) return res.roomNumber === reservation.roomNumber && (newCheckIn < actualCheckOut && newCheckOut > actualCheckIn) }) if (isReserved !== -1) throw new Error("La habitación no está disponible") reservations.push(reservation) return 'Reserva exitosa'; } const removeReservation = (id) => { const indexReservation = reservations.findIndex((res) => res.id === id) if (indexReservation === -1) throw new Error("La reservación que se busca remover no existe"); return reservations.splice(indexReservation,1)[0] } const getReservations = () => reservations; const getAvailableRooms = (checkIn, checkOut) => { const dateCheckIn = new Date(checkIn) const dateCheckOut = new Date(checkOut) const availableRooms = Array.from({ length: totalRooms }, (_, i) => i + 1) reservations.forEach((res) => { const actualCheckIn = new Date(res.checkIn) const actualCheckOut = new Date(res.checkOut) if (dateCheckIn <= actualCheckOut && dateCheckOut >= actualCheckIn) { let indexRoom = availableRooms.indexOf(res.roomNumber) if(indexRoom!==-1) availableRooms.splice(indexRoom, 1) } }) return availableRooms } return { searchReservation, getSortReservations, addReservation, removeReservation, getReservations, getAvailableRooms } }
My solution 👇
function hotelSystem(rooms) { const reservations = []; function searchReservation(id) { const index = reservations.findIndex((room) => room.id === id); if (index > -1) { return reservations[index]; } throw new Error("La reservación no existe"); } function getSortReservations() { const copy = [...reservations]; copy.sort((a, b) => { const aDate = new Date(`${a.checkIn} ${new Date().getFullYear()}`); const bDate = new Date(`${b.checkIn} ${new Date().getFullYear()}`); return aDate - bDate; }); return copy; } function addReservation(reservation) { if (!isAvailable(reservation)) { throw new Error("La habitación se encuentra ocupada"); } reservations.push(reservation); return `La reservación de ${reservation.name} fue agendada exitosamente`; } function removeReservation(id) { const index = reservations.findIndex((room) => room.id === id); if (index > -1) { const removedReservation = reservations[index]; reservations.splice(index, 1); return removedReservation; } throw new Error("La habitación que se busca remover no existe"); } function getReservations() { return reservations; } function isAvailable(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) { return false; } } } return true; } function getAvailableRooms(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:
export function hotelSystem(rooms) { let numCuartos = rooms; let reservaciones = new Array(); return { searchReservation(id) { let result = reservaciones.find(reserv => reserv.id == id); if (result == undefined) { throw new Error("La reservación no fue encontrada"); } else { return result; } }, getSortReservations() { let copiaReserv = reservaciones; copiaReserv.sort(function (a, b) { let ac = new Date(a.checkIn); let bc = new Date(b.checkIn); if (ac < bc) { return -1; } else if (ac > bc) { return 1; } else { return 0;} }) return copiaReserv; }, addReservation(reservation) { let comprueba = reservaciones.every(function (item) { if (item.roomNumber == reservation.roomNumber) { let reservIn = new Date(reservation.checkIn); let reservOut = new Date(reservation.checkOut); let itemIn = new Date(item.checkIn); let itemOut = new Date(item.checkOut); //throw new Error(reservIn+reservOut+itemIn+itemOut) if (reservIn > itemOut || reservOut < itemIn) { return true; } else { return false; } } else { return true; } }); if (comprueba) { reservaciones.push(reservation); return ""; } else { throw new Error("La habitación no está disponible") } }, removeReservation(id) { if (reservaciones.findIndex((re) => re.id == id) == -1) { throw new Error("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 (new Date(item.checkOut) < new Date(chIn) || new Date(item.checkIn) > new Date(chOut)) { return false; } else { return true; } }); let habOcu = new Array(); ocupadas.forEach(function (item) { habOcu.push(item.roomNumber); }) let resultado = new Array(); 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.
export function hotelSystem(rooms) { let reservas = [] function searchReservation(id) { let buscado = reservas.find(x => x.id == id) if (!buscado) throw new Error("La reservación no fue encontrad") else return buscado } function stringToDate(str) { // Expected format "dd/mm" const [day, month] = str.split("/"); const year = new Date().getFullYear(); const date = Date.parse(`${month}/${day}/${year}`); return date; } function getSortReservations() { //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 } function addReservation(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)) { throw new Error("La habitación no está disponible"); } reservas.push(reservation) return "Se ha reservado correctamente!!" } function removeReservation(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 } else throw new Error("La reservación que se busca remover no existe"); } function getReservations() { //todas las reservaciones. return reservas } function isAvailable(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) { return false; } } } return true; } function getAvailableRooms(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:
class Hotel { rooms = 0 reservations = []; constructor(rooms) { this.rooms = rooms; } searchReservation(id) { let found = this.reservations.find((r) => r.id === id); if (!found) throw new Error('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) ) { return true; } return false; } addReservation(newReservation) { for (let currentReservation of this.reservations) { if (newReservation.roomNumber === currentReservation.roomNumber && !this.isValidReservation(newReservation, currentReservation )) { throw new Error('"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) throw new Error("La reservación que se busca remover no existe"); return this.reservations.splice(index, 1)[0]; } getReservations() { return this.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; } } export const hotelSystem = (rooms) => new Hotel(rooms)
me impresionan las soluciones de la comunidad, uno aprende con personas que saben
Solucion
function hotelSystem(rooms) { // Creation of the hotel empty rooms const reservations = new Array(rooms); for (let i = 0; i < reservations.length; i++) { reservations[i] = { roomNumber: i + 1 }; } // Helper functions function stringToDate(str) { // Expected format "dd/mm" const [day, month] = str.split("/"); const year = new Date().getFullYear(); const date = Date.parse(`${month}/${day}/${year}`); return date; } // Function to compare 2 date ranges and check for intersection between ranges function dateRangeIntersect(range1Start, range1End, range2Start, range2End) { return range1Start <= range2End && range1End >= range2Start; } function searchReservation(id) { try { const reservation = reservations.find( (reservation) => reservation.id === id ); console.log(reservation); return reservation; } catch (error) { throw new Error(`Error, the reservation number: ${id} was not found!`); } } function getSortReservations() { const reservedRooms = reservations .filter((room) => room.hasOwnProperty("checkIn")) .sort((roomA, roomB) => { return stringToDate(roomA.checkIn) - stringToDate(roomB.checkIn); }); console.log("Currently reserved rooms: ", reservedRooms); return reservedRooms; } function addReservation(reservation) { // Reservation structure // { // id: 1, // name: "John Doe", // checkIn: "01/01", // checkOut: "02/01", // roomNumber: 1, // } const { checkIn, checkOut, roomNumber } = reservation; // Get room data const hotelRoom = reservations.find( (room) => room.roomNumber === roomNumber ); // Check if room has checkin, and checkout properties if not, // then reserve the room if ( hotelRoom.hasOwnProperty("checkIn") && hotelRoom.hasOwnProperty("checkOut") ) { // Convert date string to date const 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 intersect if ( dateRangeIntersect( reservationCheckIn, reservationCheckOut, hotelCheckIn, hotelCheckOut ) ) { const error = new Error( "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; } function removeReservation(id) { // Get reservation data const 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; } function getReservations() { console.log(reservations); return reservations; } function getAvailableRooms(checkIn, checkOut) { // Convert reservation date string to date object checkIn = stringToDate(checkIn); checkOut = stringToDate(checkOut); // Filter rooms that are available using date object data const availableRooms = reservations.filter((room) => { // Check for props checkIn and checkOut if (room.hasOwnProperty("checkIn") && room.hasOwnProperty("checkOut")) { // then compare both date ranges and return only free rooms const 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
.
.
.
.
export function hotelSystem(rooms) { const reservations = [] return { searchReservation: (id) => { const res = reservations.find((r) => r.id === id) if (!res) throw Error("La reservación no fue encontrada") else return 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)) return false } return true }) if (isPosible || reservations.length === 0) { reservations.push(reservation) return '' } else { throw Error("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 { throw Error("La reservación que se busca remover no existe") } }, getReservations: () => reservations, getAvailableRooms: (checkIn, checkOut) => { const allRooms = new Array(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)) } } } function isPosibleDate(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) } function getDate(date) { const foo = date.split('/') return new Date(...[foo[1],foo[0]]) }
Esta es mi solución
function hotelSystem(rooms) { const reservations = []; return{ searchReservation:(id)=> { const reservation = reservations.find(element => element.id === id); if(reservation) { return reservation; } else { throw new Error('La reservación no fue encontrada'); } }, getSortReservations: ()=>{ const sortedReservations = reservations.sort((a,b) => { if(a.checkIn > b.checkIn) { return 1 } if(a.checkIn < b.checkIn) { return -1 } if(b.checkIn === a.checkIn) { return 0 } }) 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 { throw new Error('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 { throw new Error('"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; } } }