Home

Awesome

patcom

patcom is a pattern-matching JavaScript library. Build pattern matchers from simpler, smaller matchers.

Pattern-matching uses declarative programming. The code matches the shape of the data.

npm install --save patcom

Simple example

Let's say we have objects that represent a Student or a Teacher.

<!-- prettier-ignore -->
  type Student = {
    role: 'student'
  }

  type Teacher = {
    role: 'teacher',
    surname: string
  }

Using patcom, we can match a person by their role to form a greeting.

<!-- prettier-ignore -->
import {match, when, otherwise, defined} from 'patcom'

function greet(person) {
  return match (person) (
    when (
      { role: 'student' },
      () => 'Hello fellow student.'
    ),

    when (
      { role: 'teacher', surname: defined },
      ({ surname }) => `Good morning ${surname} sensei.`
    ),

    otherwise (
      () => 'STRANGER DANGER'
    )
  )
}


greet({ role: 'student' }) ≡ 'Hello fellow student.'
greet({ role: 'teacher', surname: 'Wong' }) ≡ 'Good morning Wong sensei.'
greet({ role: 'creeper' }) ≡ 'STRANGER DANGER'
<details> <summary>What is <code>match</code> doing?</summary>

match finds the first when clause that matches, then the Matched object is transformed into the greeting. If none of the when clauses match, the otherwise clause always matches.

</details>

More expressive than switch

Pattern match over whole objects and not just single fields.

Imperative switch & if 😔

Oh noes, a Pyramid of doom

<!-- prettier-ignore -->
switch (person.role) {
  case 'student':
    if (person.grade > 90) {
      return 'Gold star'
    } else if (person.grade > 60) {
      return 'Keep trying'
    } else {
      return 'See me after class'
    }
  default:
      throw new Exception(`expected student, but got ${person}`)
}

Declarative match 🙂

Flatten Pyramid to linear cases.

<!-- prettier-ignore -->
return match (person) (
  when (
    { role: 'student', grade: greaterThan(90) },
    () => 'Gold star'
  ),

  when (
    { role: 'student', grade: greaterThan(60) },
    () => 'Keep trying'
  ),

  when (
    { role: 'student', grade: defined },
    () => 'See me after class'
  ),

  otherwise (
    (person) => throw new Exception(`expected student, but got ${person}`)
  )
)
<details> <summary>What is <code>greaterThan</code>?</summary>

greaterThan is a Matcher provided by patcom. greaterThan(90) means "match a number greater than 90".

</details>

Match Array, String, RegExp and more

Arrays

<!-- prettier-ignore -->
match (list) (
  when (
    [],
    () => 'empty list'
  ),

  when (
    [defined],
    ([head]) => `single item ${head}`
  ),

  when (
    [defined, rest],
    ([head, tail]) => `multiple items`
  )
)
<details> <summary>What is <code>rest</code>?</summary>

rest is an IteratorMatcher used within array and object patterns. Array and objects are complete matches, and the rest pattern consumes all remaining values.

</details>

String & RegExp

<!-- prettier-ignore -->
match (command) (
  when (
    'sit',
    () => sit()
  ),

  // matchedRegExp is the RegExp match result
  when (
    /^move (\d) spaces$/,
    (value, { matchedRegExp: [, distance] }) => move(distance)
  ),

  // ...which means matchedRegExp has the named groups
  when (
    /^eat (?<food>\w+)$/,
    (value, { matchedRegExp: { groups: { food } } }) => eat(food)
  )
)

Number, BigInt & Boolean

<!-- prettier-ignore -->
match (value) (
  when (
    69,
    () => 'nice'
  ),

  when (
    69n,
    () => 'big nice'
  ),

  when (
    true,
    () => 'not nice'
  )
)

Match complex data structures

<!-- prettier-ignore -->
match (complex) (
  when (
    { schedule: [{ class: 'history', rest }, rest] },
    () => 'history first thing on schedule? buy coffee'
  ),

  when (
    { schedule: [{ professor: oneOf('Ko', 'Smith'), rest }, rest] },
    ({ schedule: [{ professor }] }) => `Professor ${professor} teaching? bring voice recorder`
  )
)

Matchers are extractable

From the previous example, complex patterns can be broken down into simpler reusable matchers.

<!-- prettier-ignore -->
const fastSpeakers = oneOf('Ko', 'Smith')

match (complex) (
  when (
    { schedule: [{ class: 'history', rest }, rest] },
    () => 'history first thing on schedule? buy coffee'
  ),

  when (
    { schedule: [{ professor: fastSpeakers, rest }, rest] },
    ({ schedule: [{ professor }] }) => `Professor ${professor} teaching? bring voice recorder`
  )
)

Custom matchers

Define custom matchers with any logic. ValueMatcher is a helper function to define custom matchers. It wraps a function that takes in a value and returns a Result. Either the value becomes Matched or is Unmatched.

<!-- prettier-ignore -->
const matchDuck = ValueMatcher((value) => {
  if (value.type === 'duck') {
    return {
      matched: true,
      value
    }
  }
  return {
    matched: false
  }
})

...

function speak(animal) {
  return match (animal) (
    when (
      matchDuck,
      () => 'quack'
    ),

    when (
      matchDragon,
      () => 'rawr'
    )
  )
)

All the examples thus far have been using match, but match itself isn't a matcher. In order to use speak in another pattern, we use oneOf instead.

<!-- prettier-ignore -->
const speakMatcher = oneOf (
  when (
    matchDuck,
    () => 'quack'
  ),

  when (
    matchDragon,
    () => 'rawr'
  )
)

Now upon unrecognized animals, whereas speak previously returned undefined, speakMatcher returns { matched: false }. This allows us to combine speakMatcher with other patterns.

<!-- prettier-ignore -->
match (animal) (
  when (
    speakMatcher,
    (sound) => `the ${animal.type} goes ${sound}`
  ),

  otherwise(
    () => `the ${animal.type} remains silent`
  )
)

Everything except for match is actually a Matcher, including when and otherwise. Primitive value and data types are automatically converted to a corresponding matcher.

<!-- prettier-ignore -->
when ({ role: 'student' }, ...) ≡
when (matchObject({ role: 'student' }), ...)

when (['alice'], ...) ≡
when (matchArray(['alice']), ...)

when ('sit', ...) ≡
when (matchString('sit'), ...)

when (/^move (\d) spaces$/, ...) ≡
when (matchRegExp(/^move (\d) spaces$/), ...)

when (69, ...) ≡
when (matchNumber(69), ...)

when (69n, ...) ≡
when (matchBigInt(69n), ...)

when (true, ...) ≡
when (matchBoolean(true), ...)

Even the complex patterns are composed of simpler matchers.

Primitives

<!-- prettier-ignore -->
when (
  {
    schedule: [
      { class: 'history', rest },
      rest
    ]
  },
  ...
)

Equivalent explict matchers

<!-- prettier-ignore -->
when (
  matchObject({
    schedule: matchArray([
      matchObject({ class: matchString('history'), rest }),
      rest
    ])
  }),
  ...
)

Core concept

At the heart of patcom, everything is built around a single concept, the Matcher. The Matcher takes any value and returns a Result, which is either Matched or Unmatched. Internally, the Matcher consumes a TimeJumpIterator to allow for lookahead.

Custom matchers are easily implemented using the ValueMatcher helper function. It removes the need to handle the internals of TimeJumpIterator.

<!-- prettier-ignore -->
type Matcher<T> = (value: TimeJumpIterator<any> | any) => Result<T>

function ValueMatcher<T>(fn: (value: any) => Result<T>): Matcher<T>

type Result<T> = Matched<T> | Unmatched

type Matched<T> = {
  matched: true,
  value: T
}

type Unmatched = {
  matched: false
}

For more advanced use cases, the IteratorMatcher helper function is used to create Matchers that directly handle the internals of TimeJumpIterator but do not need to be concerned with a plain value being passed in.

The TimeJumpIterator works like a normal Iterator, except it can jump back to a previous state. This is useful for Matchers that require lookahead. For example, the maybe matcher would remember the starting position with const start = iterator.now, look ahead to see if there is a match, and if it fails, jumps the iterator back using iterator.jump(start). This prevents the iterator from being consumed. If the iterator is consumed during the lookahead and left untouched on unmatched, subsequent matchers will fail to match as they would never see the values that were consumed by the lookahead.

<!-- prettier-ignore -->
function IteratorMatcher<T>(fn: (value: TimeJumpIterator<any>) => Result<T>): Matcher<T>

type TimeJumpIterator<T> = Iterator<T> & {
  readonly now: number,
  jump(time: number): void
}

Use the asInternalIterator to pass an existing iterator into a Matcher.

<!-- prettier-ignore -->
const matcher = group('a', 'b', 'c')

matcher(asInternalIterator('abc')) ≡ {
  matched: true,
  value: ['a', 'b', 'c'],
  result: [
    { matched: true, value: 'a' },
    { matched: true, value: 'b' },
    { matched: true, value: 'c' }
  ]
}

Built-in Matchers

Directly useable Matchers.

Matcher builders

Builders to create a Matcher.

Matcher composers

Creates a Matcher from other Matchers.

Matcher consumers

Consumes Matchers to produce a value.

What about TC39 pattern matching proposal?

patcom does not implement the semantics of TC39 pattern matching proposal. However, patcom was inspired by the TC39 pattern matching proposal and, in-fact, has feature parity. As patcom is a JavaScript library, it cannot introduce any new syntax, but the syntax remains relatively similar.

Comparision of TC39 pattern matching proposal on the left to patcom on the right

tc39 comparision

Differences

The most notable difference is patcom implemented enumerable object properties matching, whereas TC39 pattern matching proposal implements partial object matching. See tc39/proposal-pattern-matching#243. The rest matcher can be used to achieve partial object matching.

patcom also handles holes in arrays differently. Holes in arrays in TC39 pattern matching proposal will match anything, whereas patcom uses the more literal meaning of undefined as one would expect with holes in arrays defined in standard JavaScript. The any matcher must be explicitly used if one desires to match anything for a specific array position.

Since patcom had to separate the pattern matching from destructuring, enumerable object properties matching is the most sensible. Syntactically separation of the pattern from destructuring is the most significant difference.

TC39 pattern matching proposal when syntax shape

<!-- prettier-ignore -->
when (
  pattern + destructuring
) if guard:
  expression

patcom when syntax shape

<!-- prettier-ignore -->
when (
  pattern,
  (destructuring) => guard,
  (destructuring) => expression
)

patcom offers allOf and oneOf matchers as subsitute for the pattern combinators syntax.

TC39 pattern matching proposal and combinator + or combinator

Note that the usage of and in this example is purely to capture the match and assign it to dir.

<!-- prettier-ignore -->
when (
  ['go', dir and ('north' or 'east' or 'south' or 'west')]
):
  ...use dir

patcom oneOf matcher + destructuring

Assignment to dir separated from the pattern.

<!-- prettier-ignore -->
when (
  ['go', oneOf('north', 'east', 'south', 'west')],
  ([, dir]) =>
    ...use dir
)

Additional consequence of the separating the pattern from destructuring is patcom has no need for any of:

Another difference is TC39 pattern matching proposal caches iterators and object property accesses. This has been implemented in patcom as a different variation of match, which is powered by cachingOneOf.

To see a complete comparison with TC39 pattern matching proposal and unit tests to prove full feature parity, see tc39-proposal-pattern-matching folder.

What about match-iz?

match-iz is similarly inspired by TC39 pattern matching proposal has many similarities to patcom. However, match-iz is not feature complete to TC39 pattern matching proposal, most notably missing is:

match-iz also offers a different match result API, where matched and value are allowed to be functions. The same functionality in patcom can be found in the form of functional mappers.

Contributions welcome

The following is a non-exhaustive list of features that could be implemented in the future:

patcom is seeking funding

What does patcom mean?

patcom is short for pattern combinator, as patcom is the same concept as parser combinator