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

@svartkonst/match

v1.5.0

Published

An expressive pattern-matching DSL

Downloads

83

Readme

Match: Expressive pattern matching in JavaScript

Match is a small DSL written in JavaScript that allows Erlang/Elixir/Rust-style pattern matching with a legible syntax. It supports matching against wildcards and multiple values, and ultimately resolves to a value.

It runs both in the browser and via Node, but requires support for ES205+ features.

Getting started

Via package manager

Match is published on https://npmjs.org and can be installed via package managers such as NPM or Yarn.

$ npm install @svartkonst/match

Manual installation

There is currently no browser-ready, single-file, distribution available, but the package can be downloaded and included via require or import in a compatible environment.

Basic usage

Terminology

  • Match takes any number of clauses, where each clause consists of a condition and a function. It will return itself until a final value is provided, at which point it will evaluate. match(condition, function) -> (condition, function) -> ... -> (needle) -> function(needle)
  • If a clause matches the needle, it will apply the function to the needle and return the result
  • If no clauses match, an error is thrown.
  • If no clauses are provided, an error is thrown.
  • Clauses can be added indefinitely, and evaluation will cease once a match has been found.
  • Symbol.for('_') is used as a wildcard and works similarly to _ in Erlang, Elixir, Scala, etc.

Matching against single values

Example

const _ = Symbol.for('_'); // Wildcard

const complementColour = match('blue',   () => 'red')
			      ('red', 	 () => 'blue')
			      ('green',  () => 'yellow')
			      ('yellow', () => 'green')
			      (_,        () => 'No colour found') // Prevents "No matching clause
			      
const bluesComplement = complementColour('blue'); // -> 'red'

Matching against multiple values

Both the needle and the clauses can be single values, or an array of values. Clauses are evaluated left-to-right, top-to-bottom. The clause cannot be longer than the needle, but the needle may be longer than the clause.

Example

const httpResponse = [200, 'Hello Mike'];

const parseHttpResponse = match( 200, 	     x => x) // matches, and returns [200, 'Hello Mike']
			       ([200, _],    x => x) // matches, but is never evaluated
			       ([200, _, _], x => x) // never matches - clause is longer than needle

Matching with RegEx

const httpResponse = [200, 'Hello Mike'];

const parseHttpResponse = match([_, /hello mike/i], x => x) // matches

Chaining matches

Since match expects the needle last, we can easily "cache" expressions, as seen in the above examples. Another benefit of this is that chaining matches becomes very easy, e.g. via map, filter, or Promise.then. Example:

const parseHttpResponse = match([200, _],     x => x)			   // Success!
			       ( /[3-5]\d\d/, x => x)		  	   // Well-formed error/redirect
			       ( _, 	      x => [500, 'General Error']) // Undefined behaviour 
		
/* ... */
fetch('api/articles/123')
  // Convert a Fetch Response to Promise<[status, body]>
  .then((res) => {
    const status = res.status;

    return res.text()
      .then(body => [status, body]);
  })
  // Enforce a well-formed response
  .then(match(200,         x => x)                       // Success!
             (/[3-5]\d\d/, x => x)                       // Well-formed error/redirect
             (_,           x => [500, 'General Error'])) // Undefined behaviour
  // Render the response, or render an error. 
  .then(match(200, ([_, article]) => render(article)) 
	     (_,   ([_, reason])  => render(`Error: ${reason}`));

Issues, questions, and contributions

May be filed freely using GitLab issues, or by merge request, respectively.

License

Copyright 2019 Emil Johnsen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.