A Pristine Pattern Matching Method in JavaScript

Nayantara Jeyaraj (Taro)
2 min readApr 5, 2018

--

Whenever it comes to Pattern matching, developers have almost always sought JS functions as they provide an easy way to perform pattern matching ranging from the numeral and alphanumeric strings to algebraic functions. So though, I’m here to elucidate a more sleek way in which pattern matching can be done in modern JavaScript, I feel that it’s crucial to state the predecessor(…maybe not yet!) pattern matching method, that is Regex.

Regex Pattern Matching

The most common and rudimentary method followed world-wide is the Regex Reference. Regex, that is Regular Expressions, are applied on a character string to check for the existence of a specified pattern. Regex also provides a “match and modify” functionality, to coin the term. What this means is that we can search for a particular pattern and perform a replacement, split, sub-string extractions, etc. simultaneously.

The following syntax illustrates the base structure of any regex.

/pattern/modifiers;

So, for example, we could consider the following statement.

var matchPattern = /downtown/i

i is the modifier that instructs the search to be case-sensitive. If the modifier was provided as m instead, a multi-line search for the provided string would have been performed.

These are only the very basic pattern matching regular expression and this can span over to be more complex including brackets, meta-characters, quantifiers, regExp object properties, regExp object methods, etc.

Enough about the olden yet golden methods. Let’s move on to an enhanced way of pattern matching using modern JavaScript.

match- when pattern matching

The only requirements to harness all the functionalities of this method is to have the library with match and when.

const {match, when} = require('match-when');

and the above same can be globally stated as follows.

require('match-when/register');

The reduction in the number of steps and efforts in performing pattern matching and consecutive functionalities has been reduced to specks and shown below is a simple demonstration as provided on the site’s page, to perform a factorial calculation using match — when.

const fact = match({    [when(0)]: 1,    [when()]: (n) => n * fact(n-1)});fact(10); // 3628800

Ultimately, the above matching sequence can be put to a realistic scenario demo as follows in retrieving the factorial for any provided value with a single match-when statement block.

function fact(n){    return match(n,     {        [when(0)]: 1,        [when()]: (n) => n * fact(n-1)    });}fact(10); // 3628800

The match- when repository can be found here along with further explication with regard to this function.

--

--

Nayantara Jeyaraj (Taro)

Researcher (AI Bias | NLP | Computational Linguistics) and Author of “Explicating Neural Networks”