I have a block of codes in React.js which I believe is not the best way to do it. However, I am not sure how I can simplify and optimize it. Does anyone have any ideas? Thanks so much
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");
}
CodePudding user response:
This is a very subjective and wide question but here is my suggestion.
Because the last two blocks of code have identical logic, you could make a function to simplify it, like this:
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);
CodePudding user response:
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");
}
We can create some handy inline functions to avoid duplication and some formating on conditions. Further, I don't know exactly what do dateSelectors, movieSelectors etc functions do. By optimizing those, you can create a good version of your code.