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

metch-case

v1.3.0

Published

Switch case on steroid. Enhanced branching with simplified syntax and support for conditional functions.

Downloads

7

Readme

Installation

You can install Metch using npm or yarn:

npm install metch

or

yarn add metch

Usage

To use Metch in your TypeScript project, import the desired functions from the package:

import { metch, metchReturn, DefaultBranch } from 'metch-case';

metch()

The metch function evaluates an item against a set of branches and executes the callback associated with the first matching branch. It follows a specific order of evaluation where the first matching branch is executed, and subsequent branches are ignored.

Syntax

metch<T>(item: T, branches: MatchBranches<T>, defaultBranch?: MetchBranchCallback<T>): void | Promise<void>
  • item: The item to be evaluated against the branches.
  • branches: An array of MatchBranch objects. Each MatchBranch is an array of 2 items:-
    • BranchJudge: will evaluate the item given. a judge can be a boolean, or a value of the same type as item, or a function that returns a boolean
    • BranchCallback: will execute if the judge allows it. Can be both async and sync.
  • defaultBranch: Optional default branch if all other branches not matched.

Example

import {metch, DefaultBranch} from 'metch-case';
import fs from "fs/promises"

let filePath: string | undefined = 'notValid.txt';

await metch(filePath, [
    [undefined, async (file) => {
        console.log(await fs.readFile("undefined.txt", "utf-8"));
    }], 
    ['animal.txt', async (file) => {
        console.log(await fs.readFile(file!, "utf-8"))
    }], 
    [path => path!.includes('.txt'), async (file) => {
        console.log(await fs.readFile('data.txt', "utf-8"));
    }]
], async (item) => {
  // Optional Default branch 
  console.log(await fs.readFile('default.txt', 'utf-8'))
})

metchReturn()

The metchReturn function evaluates an item against a set of branches, executes the callback associated with the first matching branch, and returns a value. It follows the same evaluation order as metch, where the first matching branch is executed and subsequent branches are ignored.

If none of the branches match, the defaultBranch callback is executed.

Syntax

metchReturn<T, U>(item: T, branches: MatchReturnBranches<T, U>, defaultBranch: MatchReturnDefaultbranch<T, U>): U | Promise<U>
  • item: The item to be evaluated against the branches.
  • branches: An array of MatchReturnBranch objects. Each MatchReturnBranch consists of a branch judge or value, and a callback function to be executed if the judge or value matches the item.
  • defaultBranch: The callback function to be executed if none of the branches match.

Example

import { metchReturn } from 'metch-case';
import fs from "fs/promises"

let filePath: string | undefined = 'animal.txt';

const fileData = await metchReturn(filePath, [
    [undefined, async (file) => {
        return await fs.readFile("undefined.txt", "utf-8");
    }], 
    ['animal.txt', async (file) => {
        return await fs.readFile(file!, "utf-8");
    }], 
    [path => path!.includes('.txt'), async (file) => {
        return await fs.readFile('data.txt', "utf-8");
    }],
], async (file) => {
    // Default Branch
    return await fs.readFile('default.txt', 'utf-8')
});

console.log(fileData);

Judge

Each branch inside metch() or metchReturn() has a judge. The item will be evaluated using this judge. If the judge allows it, then the callback inside that branch will be executed, and other branches will be ignored.

A judge<T> (Where T is the type of the item given) can be one of the following :-

  • boolean
  • (item: T) => boolean | undefined
  • T
  • Query<T>

boolean

Callback will be executed if judge is true.

Example

let filePath: string | undefined = 'animal.txt';

const fileData = await metchReturn(filePath, [
    [true, async (file) => {
        // Will always be executed and ignore other branches
        return await fs.readFile("always.txt", "utf-8");
    }]
], async (file) => {
    // Default Branch
    return await fs.readFile('default.txt', 'utf-8')
});

(item: T) => boolean | undefined

Callback will be executed if the result of the function is true.

Example

let filePath: string = 'animal.txt';

const fileData = await metchReturn(filePath, [
    [(file) => file.endsWith('.txt'), async (file) => {
        return await fs.readFile(file, "utf-8");
    }]
], async (file) => {
    // Default Branch
    return await fs.readFile('default.txt', 'utf-8')
});

T

Callback will be executed if the judge is strictly equal to item. In this case judge must be the same type as item.

Example

let filePath: string | undefined = 'animal.txt';

const fileData = await metchReturn(filePath, [
    [undefined, async () => {
      return await fs.readFile('undefined.txt', 'utf-8')
    }]
    [(file) => file!.endsWith('.txt'), async (file) => {
        return await fs.readFile(file, 'utf-8');
    }]
], async (file) => {
    // Default Branch
    return await fs.readFile('default.txt', 'utf-8')
});

Query<T>

Act as AND / OR operator for a branch's judge.

Example

const branches: MetchBranches<any> = [
     [Query.Or<any>(undefined, null, 1, (path: any) => typeof path !== 'string'), () => {
          console.log('value is not a valid string')
      }],
      [Query.And((path: any) => typeof path === 'string', 'animal'), (item) => {
          console.log('value is a string and animal')
      }],
 ];
 
 await metch('animal' as any, branches, (item) => {
      console.log('default branch')
 });

Note

It is recommended to pass the item's data type when using the Query.

let item: string | undefined = 'hello world';
Query.And<string | undefined>(...);
Query.Or<string | null>(...);