Reputation:
I'd like to make the following code more generic/page-independent so that I can use it for other projects too.
The code is checking if a certain value in the localCache exists and if the location.pathname has a certain string. If so, it should scroll to top etc.
Now it looks like this:
if (referrer == "home" && location.pathname == "projects"){
window.scrollTo(0,0);
localStorage.setItem('referrer', 'projects');
}
I'd like to make more generic so that it's not depending on the exact amount of strings of the location.pathname and so that it can refer to an X amount of location.pathnames.
I tried to make an object out of the different strings like this:
let object = {
homePage: "home",
noScrollPages: {[
"projects",
"about",
"info"
]}
}
if (referrer == homePage && (location.pathname == "/" + noScrollPages[0]) || location.pathname == "/" + noScrollPages[1] || location.pathname == "/" + noScrollPages[2]){
window.scrollTo(0,0);
localStorage.setItem("referrer", noScrollPages[0, 1, 2 or X, whichever resolves as true in the if statement]);
console.log(localStorage.getItem("referrer"));
}
So, basically I don't know how code it so that it doesn't rely on the explicit declaration of [0] or [1], because it could be X number of pages.
Thanks for any tips!
Upvotes: 0
Views: 33
Reputation: 2821
The previous solution works, but this is an alternative. If you have many different pages, it may be more efficient to use a Set, which comes with the has method, which allows you to check for existence of an element in constant time.
In this example, the location's pathname is "/projects", so locationName
evaluates to "projects"; instead of checking each page for equality to the location's pathname when the page is prepended with a "/", we check for existence of a page equal to locationName
(location without the initial slash).
let location = {pathname: "/projects"} // setting this as test (REMOVE THIS)
let object = {
homePage: "home",
noScrollPages: new Set([
"projects",
"about",
"info"
])
}
let locationName = location.pathname.substring(1) // location without first slash
if (referrer == homePage && object.noScrollPages.has(locationName)){
window.scrollTo(0,0);
localStorage.setItem("referrer", locationName);
console.log(localStorage.getItem("referrer"));
}
Upvotes: 1
Reputation: 2679
Try Array#find()
:
let object = {
homePage: "home",
noScrollPages: [
"projects",
"about",
"info"
]
}
// the matching page, or undefined if not found
const noScrollPage = object.noScrollPages.find(page => location.pathname === "/" + page);
if (referrer === homePage && noScrollPage) {
window.scrollTo(0,0);
localStorage.setItem("referrer", noScrollPage);
console.log(localStorage.getItem("referrer"));
}
Upvotes: 1