Apply pattern matching in JavaScript
npm install match-values
A lightweight, fully-typed TypeScript library that makes pattern matching simple, safe, and fun! 🎯
``bash`
npm install match-values
match-values provides a simple and powerful way to handle conditional logic using pattern matching. Think of it as a super-powered switch statement that's more flexible, readable, and completely type-safe.
`ts
import { match, last } from 'match-values'
// 1. Object Pattern Matching (for literal values)
const httpStatus = match(200, {
200: 'OK',
404: 'Not Found',
500: 'Server Error',
[last]: 'Unknown Status' // Default case
})
// Returns: 'OK'
// 2. Conditional Pattern Matching (with functions)
const getGeneration = match(1995, [
[(year) => year >= 1997, 'Gen Z'],
[(year) => year >= 1981, 'Millennial'],
[(year) => year >= 1965, 'Gen X'],
[last, 'Boomer'] // Default case
])
// Returns: 'Millennial'
`
Use plain objects to match against string or number keys. This is the most efficient way to handle a fixed set of literal values.
`ts
import { match, last } from 'match-values'
const getStatusColor = match(user.status, {
active: 'green',
pending: 'orange',
blocked: 'red',
[last]: 'grey'
})
`
Use an array of [predicate, value] tuples for more complex logic. The first predicate to return true wins.
`ts
import { match, last } from 'match-values'
const getMembershipLevel = match(user.points, [
[(points) => points >= 500, 'Gold'],
[(points) => points >= 100, 'Silver'],
[(points) => points < 100, 'Bronze']
// No default case needed if all possibilities are covered
])
`
Perfect for function composition and processing arrays. lazyMatch creates a reusable function with the pattern "baked in."
`ts
import { lazyMatch, last } from 'match-values'
const sizePattern = {
small: 12,
medium: 16,
large: 20,
[last]: 14 // Default size
}
// Use with arrays
const sizes = ['small', 'medium', 'extra-large'].map(lazyMatch(sizePattern))
// Returns: [12, 16, 14]
// Use in a function pipeline
const getFinalSize = compose(
(size) => size + 2, // Add padding
lazyMatch(sizePattern),
(item) => item.size
)({ size: 'medium' })
// Returns: 18
`
- matchlazyMatch
- Matches a value against a pattern and returns the result.
- matchCond
- Creates a reusable function that has the pattern baked in.
-
- A standalone function for when you only need conditional matching.
- last: A symbol used to define the default case in any pattern. Using a symbol prevents key collisions.
- Object Pattern: Recordstring
- A simple JavaScript object for matching literal or number keys.Array<[Predicate
- Conditional Pattern: (value: T) => boolean`) and the second is the result.
- An array of tuples, where the first item is a predicate function (
MIT