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

js-pattern-matching

v0.2.0

Published

A small library intended to provide simple Pattern Matching for JavaScript

Downloads

18

Readme

Build Status Dependency Status devDependencies Status

JS-Pattern-Matching

A small library intended to provide simple Pattern Matching capabilities for JavaScript.

var match = require('js-pattern-matching');

const sum = (list) =>  match (list) (
  ([x,...xs]) => x + sum(xs),
  ([]) => 0
)

console.log(sum([]));
// prints 0
console.log(sum([1,2,3]));
// prints 6

Installation

npm install --save js-pattern-matching

JS-Pattern-Matching leverages ES2015 syntax to make more readable and easy-to-use code. Therefore, it can only be run in ES2015-supporting environments (Node ^4 or any platform transpiled with Babel)

Babel

Babel is now supported by JS-Pattern-Matching!

To make use of it, you just need to install the Babel Plugin for JS-Pattern-Matching

npm install --save-dev babel-plugin-js-pattern-matching

Finally, you have to tell Babel to use it by adding it to your .babelrc file:

{
  "presets": [
    "es2015"
  ],
  "plugins": [
      "babel-plugin-js-pattern-matching",
  ]
}

Using JS-Pattern-Matching

We import the powerful match function by doing

var match = require('js-pattern-matching');

General Syntax

The syntax is always of the form:

match (valueToMatch)(
 listOfCommaSeparatedCaseClosures
)

Each case-closure has to be a valid ES2015 closure and is itself of the form (pattern) => closureBody

We explore different patterns in the following section

Matching literal values

The pattern for literal values is always (someVariable= matchingValue). By convention, we use the variable v which simply stands for "value", but any other valid JS identifier will do

  • We can match literal values of primitive types: number, string, boolean, null, undefined:
const getValue = (value) =>  match (value) (
  (v= 1) => "The number one",
  (v= "hello") => "A greeting",
  (v= undefined) => "An undefined value",
  (v= null) => "A null value",
  (v= true) => "The true boolean",
  (v= NaN) => "Not a number"
)

getValue(1) //returns "The number one"
getValue("hello") //returns "A greeting"
getValue(parseInt("lala")) //returns "Not a number"
getValue(2 == 2)//returns "The true boolean"
...  
  • If no value matches, MatchError is thrown:
const getNumberName = (value) =>  match (value) (
  (v= 1) => "one",
  (v= 2) => "two"
)

getNumberName(1) //returns "one"
getNumberName(5) //throws MatchError
  • If more than one case-closures match, the first takes precedence:
const getNumberName = (value) =>  match (value) (
  (v= 1) => "the first one",
  (v= 1) => "another one"
)

getNumberName(1) //returns "the first one"

Matching and binding variables

The pattern for a variable is simply (variableName)

  • A variable pattern always matches anything and binds the variable to the matching value
const length = (array) =>  match (array) (
  (array) => array.length
)

length([1,2,3]) //returns 3
length("Hello!") //returns 6
  • An annonymous variable (_) pattern always matches anything but doesn't bind the variable. It is usually used as a fallback case-closure
const isVowel = (letter) =>  match (letter) (
  (v= 'A') => true,
  (v= 'E') => true,
  (v= 'I') => true,
  (v= 'O') => true,
  (v= 'U') => true,
   (_) => false
)

isVowel('I') //returns true
isVowel('R') //returns false

Matching and Binding Class instances

The pattern for Classes is simply (ClassName) or ( variable = ClassName) to bind the class instance

  • We can match values according to their class:
const hasPermission = (user) =>  match (user) (
  (Admin) => true,
  (FreeUser) => false,
  (PremiumUser) => false
)

hasPermission(new FreeUser()) //returns false
  • We can match values according to their superclass:
const readError = (user) =>  match (user) (
  (ReferenceError) => "Something was undeclared!",
  (Error) => "Other Error"
)

readError(new ReferenceError()) //returns "Something was undeclared!"
readError(new SyntaxError()) //returns "Other Error"
  • We can bind to variables values that match to a class o superclass:
try {
  x + 1
} catch(error){
  match (error) (
  (e = ReferenceError) => "Reference error:" + e.message,
  (Error) => "Other Error"
)

//As x hasn´t been declared, it returns "Reference Error: x is not defined"
  • We can even bing to variables by ES2015 destructuring:
try {
  x + 1
} catch(error){
  match (error) (
  ({ message } = ReferenceError) => "Reference error:" + message,
  (Error) => "Other Error"
)

//As x hasn´t been declared, it returns "Reference Error: x is not defined"

Matching and Binding Array instances:

To simplify array handling, we provide specific Array matchers, based on ES2015 Array destructuring:

  • We can match an empty or nonempty array:
const sum = (array) =>  match (array) (
  ([x,...xs]) => x + sum(xs),
  ([]) => 0
)

sum([1,2,3]) // returns 6