match.flow

0.0.1 • Public • Published

match.flow

travis package downloads styled with prettier

Elm archiceture introduced update : (message, state) => state, Redux reducers became standard in JS, but unlike Elm JS lacks pattern matching and flow's disjoint union refinements via switch statements require ton of boilerplate. This library attempts to provide a better solution via poor man's pattern matching for flow projects.

Usage

// @flow
import match from "match.flow"

const counter = match({
  increment(_, n: number): number {
    return n + 1
  },
  decrement(_, n: number): number {
    return n - 1
  }
})

counter({ increment: true }, 5) //? 6
counter({ decrement: true }, 5) //? 4
counter({}, 5) //?

Probably the most compelling feature of this library is how it handlers error cases:

counter({ plus: 4 }, 3)

Above line would cause flow to report error below, meaning you'll catch error before your code is ever run:

Error: Readme.js:4
                           v
  4: const counter = match({
  5:   increment(_, n: number): number {
  6:     return n + 1
...:
 11: })
     ^ object literal. This type is incompatible with the expected param type of
 11:   matcher: Matcher<model, message>
                ^^^^^^^^^^^^^^^^^^^^^^^ object type. See: src/match.js:11
  Property `plus` is incompatible:
     11:   matcher: Matcher<model, message>
                    ^^^^^^^^^^^^^^^^^^^^^^^ property `plus`. Property not found in. See: src/match.js:11
                               v
      4: const counter = match({
      5:   increment(_, n: number): number {
      6:     return n + 1
    ...:
     11: })
         ^ object literal


Found 1 error

Fixing that code is as simple as providing plus case:

const counter = match({
  increment(_, n: number): number {
    return n + 1
  },
  decrement(_, n: number): number {
    return n - 1
  },
  plus(param: number, n: number): number {
    return n + param
  }
})

counter({ plus: 4 }, 3) //? 7

You could also combine multiple operations into single message although execution order is not guaranteed:

counter({ plus: 4, decrement: true }, 2) //? 5

Install

npm install match.flow

Package Sidebar

Install

npm i match.flow

Weekly Downloads

0

Version

0.0.1

License

MIT

Last publish

Collaborators

  • gozala