JSFiddle - React, Tailwind, and code Playground

by Andrew Maxwell

HTML

<script src="https://unpkg.com/[email protected]/mocha.js"></script>
<script src="https://unpkg.com/[email protected]/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css">
<div id="mocha"></div>

JavaScript

/*
Write a very basic regex matcher that returns true when a pattern matches a string.
In the pattern:
 . matches any single character
 * matches zero or more of the preceding character.
 Any other character is literal.
 
Pattern should match entire string, not just part.

Your goal is to get all tests to pass. Using RegExp is cheating, you're supposed to write your own.

*/
'use strict';
console.clear();

// YOUR CODE GOES BELOW

const isMatch = (str, pattern) =>
  (!str && !pattern) ||
  (pattern[1] === '*' && isMatch(str, pattern.slice(2))) ||
  (((str && pattern[0] === '.') || str[0] === pattern[0]) &&
    isMatch(str.slice(1), pattern[1] === '*' ? pattern : pattern.slice(1)));

// TESTS ARE BELOW, YOUR CODE GOES ABOVE

;(() => {
  const {expect} = chai;
  mocha.setup('bdd');
  
  const tests = [
    // [string, pattern, expectedValue]
    ['', '', true],
    ['a', 'a', true],
    ['aa', 'a', false],
    ['a', 'aa', false],
    ['a', '.', true],
    ['ab', '..', true],
    ['aa', 'a*', true],
    ['aab', 'c*a*b', true],
    ['mississippi', 'mis*is*p*.', false],
    ['mississippi', 'mis*is*ip*.', true],
    ['', '.*', true],
    ['sdkfnsdflkn', '.*', true],
    ['aaa', 'a*a', true],
    ['ab', '.*c', false],
    ['abc', '.*c', true],
    ['', 'a*b*c*', true],
    ['aaaccc', 'a*b*c*', true],
    ['aaababbccc', 'a*b*c*', false],
    ['a', 'ab*', true]
  ];
  
  tests.forEach(([str, pattern, expected]) => {
    it(`isMatch('${str}', '${pattern}') should return ${expected}`, () => {
      expect(isMatch(str, pattern)).to.equal(expected);
    });
  });
 
  mocha.checkLeaks().run();
})();