match-with

1.5.1 • Public • Published

🧩 match-with

Pattern matching object structures. Semi-related to tc39/proposal-pattern-matching.

Installation

yarn add match-with

Usage

Basic syntax:

import { match } from "match-with";
 
match(subjectany)
  .with(pattern1any, callback1: (subject, pattern1) => resultany)
  .with(pattern2any, callback2: (subject, pattern2) => resultany)
  .default(callback3: (subject) => resultany)
  .result;

Examples:

...
const subject = {
  one: 1,
  two: undefined,
  three: "3",
};
 
match(subject)
  .with({ one: 1, two: undefined }, () => {
    return "match";
  })
  .result; // "match";
 
match(subject)
  .with({ one: 2 }, () => {
    // Skipped.
  })
  .default(() => {
    return 1;
  });
 
match(subject)
  .with({ one: n => n < 2 }, () => {
    console.log(true);
  });
 
match(subject)
  .with({ four: match.EXISTS }, () => {
    // Skipped.
  })
  .with({ four: undefined }, () => {
    return 4;
  });

Community

Let me know what you think. After you ★ this project, follow me @Rygu on Twitter.

License

BSD 3-Clause license. Copyright © 2019, Rick Wong. All rights reserved.

Package Sidebar

Install

npm i match-with

Weekly Downloads

1

Version

1.5.1

License

BSD-3-Clause

Unpacked Size

12.6 kB

Total Files

6

Last publish

Collaborators

  • rickwong