title: How to write a state machine to solve the Count the smiley faces?
body: <p>I have solved the problem <a href="https://www.codewars.com/kata/583203e6eb35d7980400002a" rel="nofollow noreferrer">Count the smiley faces</a>:</p>
  <blockquote>
  <p>Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.</p>
  <p>Rules for a smiling face:</p>
  <ul>
  <li>Each smiley face must contain a valid pair of eyes. Eyes can be marked as <code>:</code> or <code>;</code></li>
  <li>A smiley face can have a nose but it does not have to. Valid characters for a nose are <code>-</code> or <code>~</code></li>
  <li>Every smiling face must have a smiling mouth that should be marked with either <code>)</code> or <code>D</code></li>
  </ul>
  <p>No additional characters are allowed except for those mentioned.</p>
  <p><strong>Valid smiley face examples:</strong> <code>:) :D ;-D :~)</code>
  <strong>Invalid smiley faces:</strong> <code>;( :&gt; :} :]</code></p>
  <p><strong>Example</strong></p>
  <pre><code>countSmileys([':)', ';(', ';}', ':-D']);       // should return 2;
  countSmileys([';D', ':-(', ':-)', ';~)']);     // should return 3;
  countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
  </code></pre>
  <p><strong>Note</strong></p>
  <p>In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.</p>
  </blockquote>
  <p>Then when I look through the solutions I find that many people use regexp. Then I want write a state machine to implement regexp and solve this problem. But I failed. This is my code:</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function countSmileys(smileys) {
    let state = smileyHasValidEye;
    return smileys.filter(smiley =&gt; {
      for (let s of [...smiley]) {
        state = state(s);
      }
      return state === true;
    }).length;
  }
  
  function smileyHasValidEye(s) {
    if (s === ':' || s === ';') {
      return smileyHasValidNose;
    }
    return smileyHasValidEye;
  }
  
  function smileyHasValidNose(s) {
    if (s === '-' || s === '~') {
      return smileyHasValidMouth;
    }
    return smileyHasValidMouth(s);
  }
  
  function smileyHasValidMouth(s) {
    if (s === ')' || s === 'D') {
      return true;
    }
    return;
  }
  
  console.log(countSmileys([':)', ';(', ';}', ':-D']));</code></pre>
  </div>
  </div>
  </p>
  <p>And the error I get is:</p>
  <pre><code>state = state(s);
                ^
  
  TypeError: state is not a function
  </code></pre>
  <p>Then I debugged my code I found the procedure doesn't enter the <code>smileyHasValidNose</code> function. Then I don't know the reason.</p>