Skip to content

Instantly share code, notes, and snippets.

@imathis
Last active December 19, 2015 02:59
Show Gist options
  • Save imathis/5887081 to your computer and use it in GitHub Desktop.
Save imathis/5887081 to your computer and use it in GitHub Desktop.
More readable coffeescript conditionals
# This is part of a simple javascript router I'm writing.
# When a link is clicked, the router checks to see if the url should trigger a route callback
# Here I demonstrate a way to improve long conditional statements with coffeescript and underscore.js
# Before: Concise but hard to read, hard to comment and hard to modify.
routeUrl: (url)->
return false if url is window.location.pathname || url.match /^http|^#/ || url.match /\.(png|gif|je?pg|pdf)$/i
url
# After: I create an array of conditionals, then using _.contains I check if any of the conditions pass
# This improves legibility and it's easier to add comments and modifications.
routeUrl: (url)->
# Do not route url if
ignore = [
# url is the current url
url is window.location.pathname
# url is a remote or in-page url
url.match /^http|^#/
# urls points to image assets
url.match /\.(png|gif|je?pg|pdf)$/i
]
# Return the url or false if it shouldn't be routed
if _.contains(ignore, true) then false else url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment