DEV Community

Cover image for Pattern-matching in JavaScript
Conan
Conan

Posted on • Updated on

Pattern-matching in JavaScript

Photo by Parham Moieni on Unsplash

Pattern-matching is something I've leaned-on a lot recently, and I'm starting to anticipate its inclusion in the language more and more. It's currently a Stage 1 proposal.

Well, maybe to help it along I can share this little library I've been tinkering with.

I've tried to, ahem, match the TC39 spec as closely as I could in anticipation of the hopeful day when I don't need to use it anymore:

import { match, when, otherwise } from 'match-iz'

let result = match(data)(
  when(pattern, result || handler),
  when(pattern, result || handler),
  otherwise(result || handler)
)
Enter fullscreen mode Exit fullscreen mode

If pattern-matching is new to you, it's essentially a declarative version of if and switch, where you describe the expected shape of your data using "patterns".

Patterns are a combination of both functions and data, and because of this certain assumptions can be made to help reduce the amount of boilerplate normally required to check that your data looks a certain way:

// Imperative:
if (typeof res?.statusCode === 'number') {
  if (res.statusCode >= 200 && res.statusCode < 300) {
    return res.body
  }
}

// Declarative:
return match(res)(
  when({ statusCode: inRange(200, 299) }, () => res.body),
  otherwise(() => {})
)
Enter fullscreen mode Exit fullscreen mode
  1. match-iz will check that statusCode is a key of res by implication of the when() being passed an object-literal { ... }.

  2. The inRange() pattern-helper guards against non-numbers before trying to determine if its input is within a certain range.

I think match-iz (along with many similar libraries) is a reasonable tool for constructing some of the more complex conditional logic we use in our JavaScript. Stuff that's usually a mess of if/else/switch statements.

If you'd like to see pattern-matching used "in the wild", I've used match-iz myself for these other little projects: sift-r and viddy

Top comments (0)