All Projects → nrdlab → Pattern Matching Ts

nrdlab / Pattern Matching Ts

Licence: mit
⚡ Pattern Matching in Typescript

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Pattern Matching Ts

Ts Pattern
🎨 A complete Pattern Matching library for TypeScript, with smart type inference.
Stars: ✭ 854 (+698.13%)
Mutual labels:  pattern-matching, matching, pattern
chemin
🥾 A type-safe pattern builder & route matching library written in TypeScript
Stars: ✭ 37 (-65.42%)
Mutual labels:  matching, pattern, pattern-matching
D4s
Dynamo DB Database Done Scala-way
Stars: ✭ 27 (-74.77%)
Mutual labels:  functional-programming, fp
Flawless
WIP Delightful, purely functional testing no-framework. Don't even try to use it at work!
Stars: ✭ 33 (-69.16%)
Mutual labels:  functional-programming, fp
Stm4cats
STM monad for cats-effect
Stars: ✭ 35 (-67.29%)
Mutual labels:  functional-programming, fp
Funfix
Functional Programming Library for JavaScript, TypeScript and Flow ✨⚡️
Stars: ✭ 596 (+457.01%)
Mutual labels:  functional-programming, fp
Frameless
Expressive types for Spark.
Stars: ✭ 717 (+570.09%)
Mutual labels:  functional-programming, fp
Bugz
🐛 Composable User Agent Detection using Ramda
Stars: ✭ 15 (-85.98%)
Mutual labels:  functional-programming, fp
Rambda
Faster and smaller alternative to Ramda
Stars: ✭ 1,066 (+896.26%)
Mutual labels:  functional-programming, fp
Motif
Recursive, data driven pattern matching for Clojure
Stars: ✭ 63 (-41.12%)
Mutual labels:  matching, pattern
Mach7
Functional programming style pattern-matching library for C++
Stars: ✭ 1,151 (+975.7%)
Mutual labels:  pattern-matching, pattern
Fkit
A functional programming toolkit for JavaScript.
Stars: ✭ 588 (+449.53%)
Mutual labels:  functional-programming, fp
Pampy.js
Pampy.js: Pattern Matching for JavaScript
Stars: ✭ 544 (+408.41%)
Mutual labels:  pattern-matching, functional-programming
Egison
The Egison Programming Language
Stars: ✭ 800 (+647.66%)
Mutual labels:  pattern-matching, functional-programming
Bow
🏹 Bow is a cross-platform library for Typed Functional Programming in Swift
Stars: ✭ 538 (+402.8%)
Mutual labels:  functional-programming, fp
Fp Jargon Zh
函数式编程术语及示例。本项目译自 https://github.com/hemanth/functional-programming-jargon
Stars: ✭ 507 (+373.83%)
Mutual labels:  functional-programming, fp
Request Compose
Composable HTTP Client
Stars: ✭ 80 (-25.23%)
Mutual labels:  functional-programming, fp
Whyhaskellmatters
In this article I try to explain why Haskell keeps being such an important language by presenting some of its most important and distinguishing features and detailing them with working code examples. The presentation aims to be self-contained and does not require any previous knowledge of the language.
Stars: ✭ 418 (+290.65%)
Mutual labels:  pattern-matching, functional-programming
Fasy
FP iterators that are both eager and asynchronous
Stars: ✭ 488 (+356.07%)
Mutual labels:  functional-programming, fp
Funland
Type classes for interoperability of common algebraic structures in JavaScript, TypeScript and Flow
Stars: ✭ 46 (-57.01%)
Mutual labels:  functional-programming, fp

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.

npm GitHub license GitHub stars GitHub forks GitHub Workflow Status


Index



Installation

yarn

yarn add pattern-matching-ts

npm

npm install --save pattern-matching-ts

Usage

MatchW

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<'r' | 'g' | 'b', number>
const either = (maybeRgb: E.Either<string, RGB>) =>
  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

import * as M from 'pattern-matching-ts/lib/match'
import { pipe } from 'fp-ts/lib/function'

interface ServerResponse<Code extends string | number> {
  readonly code: Code
}

interface Response<Body> {
  readonly response: {
    readonly body: Body
  }
}

interface Success extends ServerResponse<200>, Response<ReadonlyArray<string>> {}

interface NotFoundError extends ServerResponse<404> {}

interface ServerError extends ServerResponse<500> {
  readonly detail: string
}

type Responses = Success | NotFoundError | ServerError

const matchResponse = (response: Responses) =>
  pipe(
    response,
    M.matchW('code')({
      500: ({ detail }) => ({ message: 'Internal server error', detail }),
      404: () => ({ message: 'The page cannot be found!' }),
      200: ({ response }) => response.body,
      _: () => 'Unexpected response'
    })
  )

assert.deepStrictEqual(either(E.right({ r: 255, g: 255, b: 0 })), 'Red: 255 | Green: 255 | Blue: 0')
assert.deepStrictEqual(matchResponse({ code: 200, response: { body: ['data'] } }), ['data'])
assert.deepStrictEqual(matchResponse({ code: 500, detail: 'Cannot connect to the database' }), {
  message: 'Internal server error',
  detail: 'Cannot connect to the database'
})
assert.deepStrictEqual(matchResponse({ code: 404 }), { message: 'The page cannot be found!' })

Match

Option Match

import * as M from 'pattern-matching-ts/lib/match'
import * as O from 'fp-ts/lib/Option'

const optionMatching = M.match<O.Option<string>, string>({
  Some: (x) => `Something: ${x.value}`,
  None: () => 'Nothing'
})

assert.deepStrictEqual(optionMatching(O.some('data')), 'Something: data')
assert.deepStrictEqual(optionMatching(O.none), 'Nothing')

Default Match

import * as M from 'pattern-matching-ts/lib/match'

interface ChangeColor<T = number> {
  readonly _tag: 'ChangeColor'
  readonly value: {
    readonly r: T
    readonly g: T
    readonly b: T
  }
}
interface Move<T = number> {
  readonly _tag: 'Move'
  readonly value: {
    readonly x: T
    readonly y: T
  }
}
interface Write {
  readonly _tag: 'Write'
  readonly value: {
    readonly text: string
  }
}

type Cases = ChangeColor<number> | Move | Write
const matchMessage = M.match<Cases, string>({
  ChangeColor: ({ value: { r, g, b } }) => `Change the color to Red: ${r} | Green: ${g} | Blue: ${b}`,
  Move: ({ value: { x, y } }) => `Move in the x direction: ${x} and in the y direction: ${y}`,
  Write: ({ value: { text } }) => `Text message: ${text}`,
  _: () => 'Default message'
})

const ChangeColor = ({ r, g, b }: ChangeColor<number>['value']): ChangeColor<number> => ({
  _tag: 'ChangeColor',
  value: { r, g, b }
})

const Move = ({ x, y }: Move['value']): Move => ({
  _tag: 'Move',
  value: { x, y }
})

const Write = ({ text }: Write['value']): Write => ({
  _tag: 'Write',
  value: { text }
})

assert.deepStrictEqual(
  matchMessage(Move({ x: 500, y: 100 })),
  'Move in the x direction: 500 and in the y direction: 100'
)

assert.deepStrictEqual(
  matchMessage(ChangeColor({ r: 12, g: 20, b: 30 })),
  'Change the color to Red: 12 | Green: 20 | Blue: 30'
)

assert.deepStrictEqual(matchMessage(Write({ text: 'my message' })), 'Text message: my message')

Blog posts that introduces the API.

👉 Pattern Matching in Typescript

👉 Pipeable Pattern Matching in Typescript

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].