🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@mkrause/match

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mkrause/match

Pattern matching utility for JavaScript.

Source
npmnpm
Version
1.0.5
Version published
Weekly downloads
9
-85.94%
Maintainers
1
Weekly downloads
 
Created
Source

match.js

JavaScript pattern matching utility.

Usage

Using an object:

    const { match } = require('@mkrause/match');
    const result = match('foo', {
        foo: 42,
        bar: 43,
    });
    result === 42;

Using a predicate list:

    const { match } = require('@mkrause/match');
    const result = match({ value: 42 }, [
        match.case(({ value }) => value > 0, +1),
        match.case(({ value }) => value == 0, 0),
        match.case(({ value }) => value < 0, -1),
    ]);
    result === 1;

Custom match semantics

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

    const { matcher } = require('@mkrause/match');
    
    const match = matcher(subject => {
        return { 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 } }
    const { matchType, matchSingleKey } = require('@mkrause/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

FAQs

Package last updated on 10 Apr 2017

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