Tengo un bloque de códigos en React.js que creo que no es la mejor manera de hacerlo. Sin embargo, no estoy seguro de cómo puedo simplificarlo y optimizarlo. ¿Alguien tiene alguna idea? Muchas gracias
const url = new URL(window.location.href); let date = ""; let locationId = 0, movieId = 0; const urlDate = url.searchParams.get("date"); if (urlDate) { if (dateSelectors.filter((x) => x.code === urlDate).length > 0) date = urlDate; else toast.error("Date retrieved from the URL is invalid"); } const urlMovie = url.searchParams.get("movieId"); if (urlMovie && urlMovie !== "0") { if ( !Number.isNaN(+urlMovie) && movieSelectors.filter((x) => x.code === urlMovie).length > 0 ) movieId = urlMovie; else toast.error("Movie Id retrieved from the URL is invalid"); } const urlLocation = url.searchParams.get("locationId"); if (urlLocation && urlLocation !== "0") { if ( !Number.isNaN(+urlLocation) && locationSelectors.filter((x) => x.code === urlLocation).length > 0 ) locationId = urlLocation; else toast.error("Theatre Id retrieved from the URL is invalid"); }Esta es una pregunta muy subjetiva y amplia, pero aquí está mi sugerencia.
Debido a que los dos últimos bloques de código tienen una lógica idéntica, podría crear una función para simplificarlo, así:
const handleUrls = (url, selector) => { if (url && url !== "0") { if ( !Number.isNaN(+url) && selector.filter((x) => x.code === url).length > 0 ) locationId = urlLocation; else toast.error(`The ${url} URL is invalid`); } }; handleUrls(urlLocation, locationSelectors); handleUrls(urlMovie, movieSelectors);const url = new URL(window.location.href); const getValue = (key)=> url.searchParams.get(`${key}`) const toastOnError = (message)=> toast.error(`${message}`) let date = ""; let locationId = 0, movieId = 0; const urlDate = getValue("date"); if (urlDate) { date = (dateSelectors.filter(x => x.code === urlDate).length > 0) ? urlDate : ""; !date && toastOnError("Date retrieved from the URL is invalid") } const urlMovie = getValue("movieId"); if (urlMovie && urlMovie !== "0") { movieId = (!Number.isNaN(+urlMovie) && movieSelectors.filter(x => x.code === urlMovie).length > 0) ? urlMovie : movieId; !movieId && toastOnError("Movie Id retrieved from the URL is invalid"); } const urlLocation = getValue("locationId"); if (urlLocation && urlLocation !== "0") { locationId = (!Number.isNaN(+urlLocation) && locationSelectors.filter(x => x.code === urlLocation).length > 0) ? urlLocation: locationId; !locationId && toastOnError("Theatre Id retrieved from the URL is invalid"); }Podemos crear algunas funciones útiles en línea para evitar la duplicación y algunos formateos en las condiciones. Además, no sé exactamente qué hacen las funciones dateSelectors, movieSelectors, etc. Al optimizarlos, puede crear una buena versión de su código.