I feel like I'm repeating a ton of code here and there's got to be a better way to do this but am just completely spacing right now. I basically have an else if
clause that, if their conditions are met, repeat the same code, but I'm also repeating the same code in the else
statement along with a few other conditions.
What would be the best way to condense this? Could I create one master browser check function?
var searchEngine = document.referrer;
if ($('#userName').length){
if (/Chrome/.test(searchEngine)){
browser = "Chrome";
} else if (/Firefox/.test(searchEngine)){
browser = "FF";
} else if (/Safari/.test(searchEngine)){
browser = "Safari";
}
} else if (/ip(hone|od|ad)/i.test(searchEngine)){
if (/Chrome/.test(searchEngine)){
browser = "Chrome";
} else if (/Firefox/.test(searchEngine)){
browser = "FF";
} else if (/Safari/.test(searchEngine)){
browser = "Safari";
}
} else {
if (/Chrome/.test(searchEngine)){
browser = "Chrome";
} else if (/Firefox/.test(searchEngine)){
browser = "FF";
} else if (/Safari/.test(searchEngine)){
browser = "Safari";
} else if (/ip(hone|od|ad)/i.test(searchEngine)){
browser = "iOS";
} else if (/(?:(compatible;.*)?Trident\/7.0)/ig.test(searchEngine)){
version = 11;
browser = "IE";
} else if (/MSIE (\d+\.\d+);/.test(searchEngine)){
browser = "IE";
}
}
1 Answer 1
The Chrome, Firefox, and Safari duplicated code exists as the first part of every conditional and those three can be moved outside. Then have all of the other logic in an else. You'll end up with the $('#userName').length
and /ip(hone|od|ad)/i.test(searchEngine)
being empty. The reason I haven't provided a code example is because only you can decide if that's a problem or not.
-
\$\begingroup\$ But I can't really do that cause I have to check if an element exists first, then check if it's on an iOS device and then have a fallback. Unless I'm not understanding you correctly. (code sample might be helpful) \$\endgroup\$Delmon Young– Delmon Young2014年12月23日 21:10:32 +00:00Commented Dec 23, 2014 at 21:10
-
\$\begingroup\$ I actually didn't provide a code sample on purpose because those checks you mention don't actually do anything as the code stands. Regardless of your checks, if searchEngine contains "Chrome", "Firefox", or "Safari", browser will ALWAYS be assigned as a result of that and the rest ignored. \$\endgroup\$moarboilerplate– moarboilerplate2014年12月23日 21:13:42 +00:00Commented Dec 23, 2014 at 21:13
-
\$\begingroup\$ I see what you mean. I'll update my answer. \$\endgroup\$moarboilerplate– moarboilerplate2014年12月23日 21:14:43 +00:00Commented Dec 23, 2014 at 21:14
-
\$\begingroup\$ I was overthinking this. Your correct I can just move the duplicate parts outside of the conditionals and have those execute first. Thanks for the help. \$\endgroup\$Delmon Young– Delmon Young2014年12月23日 21:31:30 +00:00Commented Dec 23, 2014 at 21:31