⚡ Pattern Matching in Typescript
Pattern matching in Typescript.
Pattern Matching is a declarative much more powerful and less verbose alternative to imperatives "if/else" conditions.
A definition can be found inside Scala Documentation
“Pattern matching tests whether a given value (or sequence of values) has the shape defined by a pattern, and, if it does, binds the variables in the pattern to the corresponding components of the value (or sequence of values).”
In Functional Programming languages, there're built-in keywords for Pattern Matching. Typescript though is one language that works very well with Functional Programming but lacks this feature.
This package aims to bring Pattern Matching feature to Typescript through Discriminated Union Types / Algebraic Data Types.
yarn
yarn add pattern-matching-tsnpm
npm install --save pattern-matching-tsMatchW
Option MatchW
import * as M from 'pattern-matching-ts/lib/match'
import { pipe } from 'fp-ts/lib/function'
import * as O from 'fp-ts/lib/Option'
const optionMatching = (o: unknown) =>
pipe(
o,
M.matchW('_tag')({
Some: ({ value }) => 'Something: ' + value,
None: () => 'Nothing',
_: () => 'Default'
})
)
assert.deepStrictEqual(optionMatching(O.some('data')), 'Something: data')
assert.deepStrictEqual(optionMatching(O.none), 'Nothing')
assert.deepStrictEqual(optionMatching((undefined as unknown) as O.None), 'Default')Either MatchW
import * as M from 'pattern-matching-ts/lib/match'
import { pipe } from 'fp-ts/lib/function'
import * as E from 'fp-ts/lib/Either'
type RGB = Record
const either = (maybeRgb: E.Either) =>
pipe(
maybeRgb,
M.matchW('_tag')({
Left: ({ left }) => 'Error: ' + left,
Right: ({ right: { r, g, b } }) => `Red: ${r} | Green: ${g} | Blue: ${b}`
})
)
assert.deepStrictEqual(either(E.right({ r: 255, g: 255, b: 0 })), 'Red: 255 | Green: 255 | Blue: 0')Default MatchW
…Match
Option Match
import * as M from 'pattern-matching-ts/lib/match'
import * as O from 'fp-ts/lib/Option'
const optionMatching = M.match, string>({
Some: (x) => `Something: ${x.value}`,
None: () => 'Nothing'
})
assert.deepStrictEqual(optionMatching(O.some('data')), 'Something: data')
assert.deepStrictEqual(optionMatching(O.none), 'Nothing')Default Match
…Blog posts that introduces the API.
Pattern Matching in Typescript
No open issues yet, or sync has not completed.