Skip to content

miutamihai/js-pattern

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

js-pattern

Tiny javascript library for pattern matching. Inspired by ts-pattern.

Dependencies

None.

Installation

  • Using npm: npm i @nerdscomputing/js-pattern
  • Using yarn: yarn add @nerdscomputing/js-pattern

Usage

The library exposes a single function called match.

Use the .with operator to add cases. .with receives two parameters:

  • condition -> condition for the match, can be literal, an array of literals, a boolean or a lambda
  • lambda -> function to run on match

The .with operator can be chained endlessly.

Use the .like operator for comparing object fields. It can be endlessly chained and combined with the .with operator.

import match from 'js-pattern'

const matchResponse = response => match(response)
    .like({status: 200}, () => console.log('OK'))
    .like({status: 400}, () => console.log('Bad arguments'))
    .like({status: 404}, () => console.log('Not found'))
    .otherwise(() => console.log('Unknown error'))

Use the .has operator for checking for object fields. It can be endlessly chained and combined with the .with and .like operators.

import match from 'js-pattern'

const person = {
    name: 'Mihai',
    job: 'Programmer'
}

const isEmployed = () => match(person)
    .has('job', () => console.log('Employed'))
    .otherwise(() => console.log('Unemployed'))

Use the .otherwise operator to add a default case. It takes a single parameter, lambda, which is the function to be run upon match. Using the .otherwise operator will run the matching.

Use the .execute to run the actual matching.

import match from 'js-pattern'

const sayHiToMihai = name => match(name)
    .with('Mihai Miuta', () => console.log('Hi, my creator'))
    .with(name === 'Mihai Radulescu', () => console.log('Hi, fellow Nerd Mihai'))
    .with(() => name === 'Other Mihai', () => console.log('Hi, fellow Mihai'))
    .otherwise(() => console.log(`Hi, person who's not Mihai`))

About

Tiny javascript library for pattern matching

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published