title: How to implement a complex decision in javascript
body: <p><strong>Context:</strong></p>
  
  <p>We're writing logic for a signup component. If the user is not authenticated, the form should appear. If/when the user is authenticated it should redirect to one of several places. If there are unread messages, redirect to the first one. If there are no unread messages, redirect to the dashboard.</p>
  
  <p>There is one more scenario we need to handle. When a new message arrives, a user can receive an email notification with a link to the signin form <strong>plus</strong> a query param with the ID of the specific message. Ex: <code>/signin?new_message=42</code>. In these situations, the signin form should appear if the user is not currently authenticated; if/when the user is authenticated, redirect to that specific message.</p>
  
  <p><strong>My question:</strong></p>
  
  <p>How can we implement this in an elegant and <em>extendible</em> way? </p>
  
  <p>I <em>suspect</em> that a <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">state machine</a> is the right tool for this job, but I am open to other approaches. I emphasized the word <em>extendible</em> because this is not code golf! I'm looking for a real-life solution that can scale gracefully to include additional business logic in the future. </p>
  
  <p>NOTE: I don't actually care about javascript specifically, but StackOverflow best practices emphasize specificity and JS is the language I'm using. Therefore, an acceptable answer can use pseudo code as long it is conceptually compatible with javaScript. (Don't pseudo-code something that only works in Go)</p>
  
  <p>Spoiler alert! Here's the WRONG answer:</p>
  
  <pre><code>if (authed &amp;&amp; hasUnreadMessages &amp;&amp; !clickFromEmail) {
    redirect = `/messages/${fistUnreadMessageId}`;
  }
  if (authed &amp;&amp; !hasUnreadMessages &amp;&amp; !clickFromEmail) {
    redirect = `/dashboard`
  }
  if (authed &amp;&amp; clickFromEmail) {
    redirect = `/messages/${messageIdFromQueryString}`
  }
  ...
  </code></pre>
  
  <p>^ A messy tangle of nested conditionals is the <em>problem</em> we're trying to solve.</p>
  
  <p><strong>NOT my question</strong></p>
  
  <p>This is a real-life example, but the main goal of my question is to learn about implementing complex decision logic. So I am not interested in architectural solutions that avoid this logic entirely. Ex: "Create different forms/endpoints to handle the different scenarios"</p>
  
  <p>I'm also not interested in solutions that rely on a specific library. Ex: "You should just use ComplexSigninLibrary.js"</p>
  
  <p>Product design or UX advice also misses the point of this question Ex: "It would be a better user experience to link directly from the email notifications to the new messages..."</p>