-2

I have created this function to check the pathname of these 3 products, but I think it looks a bit repetitive, so I'm wondering if there's a way to make it more optimised

 function checkPathName() {
    return (
    window.location.pathname !== '/groovybaby-/241315' && 
    window.location.pathname !== '/cleopatra/241162' && 
    window.location.pathname !== '/cumulus/528678'
)}

checkPathName();

I'm expecting this function to return false for those pathnames

gog
  • 10,367
  • 2
  • 24
  • 38
PattRana
  • 17
  • 3
  • 2
    Put them in an array and check if the array includes the value – Harun Yilmaz Jan 20 '23 at 09:41
  • You could use early returns – Nico Haase Jan 20 '23 at 09:41
  • `return !['/a', '/b', '/c'].includes(location.pathname)` – CherryDT Jan 20 '23 at 09:43
  • 1
    "Optimised" can mean a few things in JS. Are you asking about faster executing JS? Or neater code? Or smaller file sizes? (I would suggest aiming for neat and readable code, but it's worth being specific) – DBS Jan 20 '23 at 09:49
  • Duplicate of https://stackoverflow.com/questions/9121395/javascript-the-prettiest-way-to-compare-one-value-against-multiple-values – T.J. Crowder Jan 20 '23 at 09:49
  • 1
    Three lines of code is 'a bit repetitive'? What do you think you can achieve 'optimising' three lines of code? If you take anything away from this question let it be this: don't waste time on micro-optimisation. Go do something more creative instead. – Tangentially Perpendicular Jan 20 '23 at 09:52

2 Answers2

3

A better option would be to have a Set of these paths and then check if the pathname is in the set:

const PATHS = new Set([
    '/groovybaby-/241315', 
    '/cleopatra/241162', 
    '/cumulus/528678',
]);

function checkPathName() {
    return !PATHS.has(window.location.pathname)
}

You actually don't even need a separate function for this.

gog
  • 10,367
  • 2
  • 24
  • 38
  • 1
    For not recalling more times window.location, we should as well create a variable for it: `const currentPathName = window.location.pathname;` – Levi D. Jan 20 '23 at 09:51
-1

you can create array of URLs and then check if it includes your current path.

function checkPathName() {
   let urls = ['/groovybaby-/241315', '/cleopatra/241162', '/cumulus/528678' ];
   if ( urls.includes(window.location.pathname) )
      return false
}
Mateusz
  • 175
  • 9