New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

case-match

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

case-match

JavaScript case matching library.

latest
Source
npmnpm
Version
3.0.0
Version published
Weekly downloads
5
-44.44%
Maintainers
1
Weekly downloads
 
Created
Source

case-match

npm GitHub Actions MIT Types

JavaScript case matching utility. With TypeScript support.

Usage

The match function takes a value, and a list of cases, and returns either the first case that matches, or an exception otherwise.

import match from 'case-match';

const type = 'foo';
const result = match(type, {
    foo: 42,
    bar: 43,
    baz: 44,
});
result === 42;

A case result can be either a plain value, or a function:

const fruit = 'orange';
const result = match(fruit, {
    apple: 'Apple Pie',
    orange: () => 'Orange Juice',
});
result === 'Orange Juice';

A default case can be specified as fallback. A special symbol match.default is available to use as the key for the default case.

const fruit = 'pear';
const result = match(fruit, {
    apple: 'Apple Pie',
    orange: 'Orange Juice',
    [match.default]: fruit => processOther(fruit),
});

If no case matches, and no fallback is given, an exception is thrown.

Custom match semantics

You can create your own custom match function. For example, let's say we have a React application that makes use of actions that conform to the Flux Standard Action (FSA) protocol. We could create a matcher as follows:

import { matcher } from 'case-match';

const match = matcher(subject => ({
    discriminator: subject.type,
    body: subject,
}));

const action = { type: 'CREATE_USER', error: false, payload: { name: 'John' } };
const result = match(action, {
    CREATE_USER: ({ error, payload }) => doSomethingWith(payload),
});

We supply a couple of common matchers out of the box:

  • match: generic matcher
  • matchType: match on objects with a type property
  • matchSingleKey: match on objects with a single property, e.g. { MY_TYPE: { value: 42 } }
import { matchType, matchSingleKey } from 'case-match';

const action = { type: 'CREATE_USER', error: false, payload: { name: 'John' } };
matchType(action, {
    CREATE_USER: ({ error, payload }) => doSomethingWith(payload),
});

matchSingleKey({ CREATE_USER: { name: 'John' } }, {
    CREATE_USER: user => doSomethingWith(user),
});

Similar libraries

Keywords

case

FAQs

Package last updated on 16 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts