npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

lil-match

v1.2.1

Published

Super small pattern matching library for TS projects

Downloads

3

Readme

Super small pattern matching library for TS projects

  • [x] Only 259 B when minified & gziped
  • [x] Designed for TypeScript projects
  • [x] No dependencies

📦 Install

npm i -S lil-match
yarn add lil-match

💻 Use

import { match } from 'lil-match'

type Response =
  | { type: 'pending' }
  | { type: 'failed'; error: Error }
  | { type: 'ready'; data: { name: 'John' } }

let input: Response

let output: string = match(input)
  .with({ type: 'pending' }, (res) => `⏳`)
  .with({ type: 'failed' }, (res) => `⚠️ ${res.error.message}`)
  .with({ type: 'ready' }, (res) => `👋 ${res.data.name}!`)
  .exhaustive('Unhandled input')

📖 Docs

match(input)

Returns an object based on input with methods for chaining. Use .with method to create patterns, close the chain with .otherwise, .run, or .exhaustive methods.

Params

  • input
    • a value you'll be testing

Returns

Object with methods:

Examples

let input: 'something' | 'nothing'

let output = match(input)
  .with('something', (res) => res)
  .with('nothing', (res) => res)
  .exhaustive('Unhandled input')

.with(...patterns, callback(match))

Create a match pattern based on input. The pattern can be an object, primitive value, Number, String, Boolean, Symbol, BigInt constructors for creating wildcard patterns, or custom type guard function. Use callback to access matched value. Returns an object with match methods for chaining.

Params

  • ...patterns
    • can be an object, literal value, primitive, Number, String, Boolean, Symbol, BigInt constructors, or type predicate
  • callback(match)
    • access matched value
    • returned value will be used for the output type of end of match chain

Returns

Object with methods:

Examples

Literals
let input: 'something' | 'nothing'

let output = match(input)
  .with('something', (res) => res)
  .with('nothing', (res) => res)
  .exhaustive('Unhandled input')
Enums
enum Type {
  ONE,
  TWO,
}

let input: Type

let output = match(input)
  .with(Type.ONE, (res) => res)
  .with(Type.TWO, (res) => res)
  .exhaustive('Unhandled input')
Match primitives with constructors
let input: string | number

let output = match(input)
  .with(String, (res) => res)
  .with(Number, (res) => res)
  .exhaustive('Unhandled input')
Objects
let input:
  | { type: 'pending' }
  | { type: 'failed' }
  | { type: 'ready'; data: { type: 'image' } | { type: 'text' } }

let output = match(input)
  .with({ type: 'ready', data: { type: 'image' } }, (res) => res)
  .with({ type: 'ready', data: { type: 'text' } }, (res) => res)
  .with({ type: 'pending' }, (res) => res)
  .with({ type: 'failed' }, (res) => res)
  .exhaustive('Unhandled input')
Multiple patterns

Specify multiple patterns as arguments. The last parameter should be a callback.

let input: string | number | bigint

let output = match(input)
  .with(Number, BigInt, (res) => console.log('Number-like'))
  .with(String, (res) => console.log('String'))
  .exhaustive('Unhandled input')
Custom type guard

Define type guard function and pass it as a pattern to narrow the input type.

interface User {
  id: number
  name: string
}

let input: { data: User } | { data: number[] } | { data: 'literal' }

function isUser(input: unknown): input is User {
  return (
    typeof input === 'object' &&
    input != null &&
    'id' in input &&
    'name' in input
  )
}

let output: string = match(input)
  .with({ data: isUser }, (res) => `User: ${res.data.name}`)
  .with({ data: Array.isArray }, (res) => `Array of: ${res.data}`)
  .with({ data: 'literal' }, (res) => res.data)
  .exhaustive('Unhandled input')

.run()

Execute match chain and return result. If all cases are matched result value will be exactly what was returned in the callback of .with method. However, if even one case was not handled result will include undefined.

Params

The method does not accept any arguments.

Returns

The output of match chain. Can be optional if not all the conditions have been matched using .with patterns. Use .otherwise if you want to provide a fallback value or to handle unknown cases.

Examples

Every case is handled
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' | 'nothing' = match(input)
  .with({ text: 'something' }, (res) => res.text)
  .with({ text: 'nothing' }, (res) => res.text)
  .run()
Unhandled case
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' | undefined = match(input)
  .with({ text: 'something' }, (res) => res.text)
  .run()
No cases
let input: { text: 'something' } | { text: 'nothing' }

let output: undefined = match(input).run()

.exhaustive(errorMessage)

Use the exhaustive method to enforce matching in every possible case. If match has any unhandled errors it will show TS error during the type check. Plus it will throw an error if the unhandled case will be passed as input. This method returns strictly what has been returned using callback of .with. This method is designed to check strongly typed cases.

Params

  • errorMessage
    • the message of Error which will be thrown in case of an unhandled case
    • ideally, the error should never throw, but it's useful to catch cases not typed yet immediately

Returns

The output of match chain. Use .run for an optional result, or .otherwise if you need to handle an unknown condition.

Examples

Every case is handled
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' | 'nothing' = match(input)
  .with({ text: 'something' }, (res) => res.text)
  .with({ text: 'nothing' }, (res) => res.text)
  .exhaustive('Unhandled input')
Unhandled case
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' = match(input)
  .with({ text: 'something' }, (res) => res.text)
  // will show error of unhandled `{ text: 'nothing' }` case during the type check
  // @ts-expect-error
  .exhaustive('Unhandled input')

.otherwise(callback(unmatched))

Just like .run, .otherwise execute match chain and returns the result, but can be used with a callback to handle unknown value. The return value of callback will be combined with the output type of the match chain. It's not possible to call .otherwise if Every case is handled.

Params

  • callback(unmatched)

Returns

The output of match chain, plus the result of the callback.

Examples

Unhandled case
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' | null = match(input)
  .with({ text: 'something' }, (res) => res.text)
  .otherwise((unmatched) => {
    console.log(unmatched.text) // will be 'nothing'
    return null
  })
No cases
let input: { text: 'something' } | { text: 'nothing' }

let output: null = match(input).otherwise((unmatched) => {
  console.log(unmatched.text) // will be 'something' or 'nothing'
  return null
})
Impossible to call when all cases are matched
let input: { text: 'something' } | { text: 'nothing' }

let output: 'something' | 'nothing' = match(input)
  .with({ text: 'something' }, (res) => res.text)
  .with({ text: 'nothing' }, (res) => res.text)
  // Impossible to call because all conditions are matched
  // .otherwise((_) => '🤷‍♂️')
  .run()

🙋‍♂️ FAQ

How it's different from the other solutions?

The difference is mostly in the size of the library. It's designed to be as small as possible and not to handle every possible use case. A tiny footprint of the library means more understandable code, simpler types, and almost no effect on your app bundle size.

If your project requires advanced pattern matching features, please have a look at amazing ts-pattern by @gvergnaud.

Is it better than native switch & case?

It's not better, it's just a bit different. In my opinion, the result code is cleaner, especially when you need to handle nested unions, for example:

let input:
  | { type: 'idle' }
  | { type: 'ready'; data: { type: 'image' } | { type: 'text' } }

let output = match(input)
  .with({ type: 'idle' }, (res) => res)
  .with({ type: 'ready', data: { type: 'image' } }, (res) => res)
  .with({ type: 'ready', data: { type: 'text' } }, (res) => res)
  .exhaustive('Unhandled input')
let input:
  | { type: 'idle' }
  | { type: 'ready'; data: { type: 'image' } | { type: 'text' } }

function exhaustive(_: never) {
  throw new Error('Unhandled input')
}

switch (input.type) {
  case 'idle': {
    /* do something */
    break
  }
  case 'ready': {
    switch (input.data.type) {
      case 'image': {
        /* do something */
        break
      }
      case 'text': {
        /* do something */
        break
      }
      default:
        exhaustive(input.data)
    }
    break
  }
  default:
    exhaustive(input)
}

Additionally switch statement can't handle checking against a type of value, which is pretty easy with lil-match by using constructors.

let input: number | string | boolean

let output = match(input)
  .with(Number, (res) => res)
  .with(String, (res) => res)
  .with(Boolean, (res) => res)
  .exhaustive('Unhandled input')
let input: number | string | boolean

function exhaustive(_: never) {
  throw new Error('Unhandled input')
}

if (typeof input === 'string') {
  /* do something */
} else if (typeof input === 'number') {
  /* do something */
} else if (typeof input === 'boolean') {
  /* do something */
} else {
  exhaustive(input)
}

Is this library code compatible with IE11?

No, the library depends on rest parameters, arrow functions, object shorthand method definitions, and other features (but polyfill-able) from modern JS. If you need to support older browsers, include lil-match from node_modules to your compiler white-list.

🙏 Acknowledgments


MIT © John Grishin