• Stars
    star
    528
  • Rank 81,042 (Top 2 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated 12 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🐚 Pattern matching for modern JavaScript

match-when - Pattern matching for modern JavaScript

Circle CI Coverage Status deps Version extra Twitter Follow Get help on Codementor Slack

Finally a clear, succinct and safe syntax to do Pattern Matching in modern JavaScript. (backstory)

Shameless plug

Usage

The setup is pretty simple, simply require the library with match and when and you are ready to go!

const {match, when} = require('match-when');

or globally

require('match-when/register'); // `match` and `when` are now globally available

Now let's see how we would write a factorial function:

const fact = match({
  [when(0)]: 1,
  [when()]: (n) => n * fact(n-1)
});

fact(10); // 3628800

Clear and simple right?

Alternatively, match(<input>, patternSpecification) can be used to instantly perform a match:

function fact(n){
  return match(n, {
    [when(0)]: 1,
    [when()]: (n) => n * fact(n-1)
  });
}

fact(10); // 3628800

Note that when() is a catch-all pattern and, if used, should always be the last condition. If you forget it match() will throw a MissingCatchAllPattern exception if nothing was matched.

Setup
npm i match-when -S
High Order Functions

match works well with high order functions like map, filter (and so on) too:

[2, 4, 1, 2].map(match({
  [when(1)]: "one",
  [when(2)]: "two",
  [when()]: "many"
}));

// [ 'two', 'many', 'one', 'two' ]
Arrays

It also works with arrays:

function length(list){
  return match({
    [when([])]: 0,
    [when()]: ([head, ...tail]) => 1 + length(tail)
  })(list);
}

length([1, 1, 1]); // 3
OR

Sadly JavaScript does not offer us a way to overload operators so we're stuck with when.or:

function parseArgument(arg){
  return match({
    [when.or("-h", "--help")]: () => displayHelp,
    [when.or("-v", "--version")]: () => displayVersion,
    [when()]: (whatever) => unknownArgument.bind(null, whatever)
  })(arg);
}

parseArgument(process.argv.slice(1)); // displayHelp || displayVersion || (binded)unknownArgument
AND
const protocols = repositories.map(match({
  [when.and({useGit:true}, {useSSH: true})]: 'git+ssh:',
  [when.and({useGit:true}, {useHTTP: true})]: 'git+http:',
  [when.and({useGit:true}, {useHTTPS: true})]: 'git+https:',
  [when()]: 'unsupported:'
}))
Regular Expressions

match-when supports regular expressions as well:

['hey.com', '[email protected]', '[email protected]', 'wat'].filter(match({
  [when(/\S+@\S+\.\S+/)]: false, // **seems** to be a valid email (unsafe regex for doc purpose only)
  [when()]: true // the email could be invalid, return it
}));

// ['hey.com', 'wat']
Range
[12, 42, 99, 101].map(match({
  [when.range(0, 41)]: '< answer',
  [when.range(43, 100)]: '> answer',
  [when(42)]: 'answer',
  [when()]: '< 0, or > 100'
}));

// ['< answer', 'answer', '> answer', '< 0, or > 100']

Supported patterns:

  • { x1: pattern1, ..., xn: patternn } - matches any object with property names x1 to xn matching patterns pattern1 to patternn, respectively. Only the own properties of the pattern are used.
  • [pattern0, ..., patternn] - matches any object with property names 0 to n matching patterns pattern0 to patternn, respectively.
  • /pattern/flags - matches any values than pass the regular expression test
  • when.range(low, high) matches any number value in the range [low, high], low and high included.
  • when.or(pattern0, ..., patternn) - matches if at least one pattern matches.
  • when.and(pattern0, ..., patternn) - matches if every pattern matches.

Todo:

I will accept PR with their associated tests for the following features:

  • define and implement some syntax to support wildcards

todo-list inspired by pattern-match from dherman.

* well, of course, they are not keywords but simple functions

Why/How? - the slides

capture d ecran 2016-03-17 23 35 44

Why/how? - the talk in french (sorry)

capture d ecran 2016-03-17 23 35 44

Development sponsored by iAdvize

I work at iAdvize as a Lead Developer and Architect. iAdvize is the leading real-time customer engagement platform in Europe and is used in 40 different countries. We are one of the french startup with the fastest growth and one of the greatest place to work in France.

We are looking for a NodeJS backend developer, a Scala backend developer, a JavaScript frontend developer, a Full-stack Developer and a DevOps System Engineer in Paris or Nantes. Send me a tweet if you have any questions!

The Story

Changelog

More Repositories

1

mailchecker

📫 Cross-language temporary (disposable/throwaway) email detection library. Covers 55 734+ fake email providers.
PHP
1,486
star
2

check-build

🎯 Check-build - Verifies that your NodeJS project follows team conventions, is well written, up to date and secure.
JavaScript
686
star
3

spinners

🛎 60+ Elegant terminal spinners for Rust
Rust
462
star
4

jq.node

jq.node - like jq but WAY MORE powerful (300+ helpers 🔥 & 1.45M modules 😱)
JavaScript
418
star
5

dot-clipboard

👝 dot-clipboard monitors your clipboard and runs scripts based on its content
JavaScript
416
star
6

node-language-detect

🇫🇷 NodeJS language detection library using n-gram
JavaScript
375
star
7

node-request-retry

💂‍♂️ Wrap NodeJS request module to retry http requests in case of errors
JavaScript
346
star
8

gron

gron - Make JSON greppable!
JavaScript
294
star
9

forever-webui

[unmaintained] 📡 A simple web UI for efficient NodeJS processes administration
JavaScript
293
star
10

ui-predicate

Finally a Predicate/Rule Editor UI component for the Web 🚀
JavaScript
152
star
11

node-unidecode

📃 ASCII transliterations of Unicode text
JavaScript
130
star
12

import-tweets-to-mastodon

How to import tweets to mastodon (e.g. https://framapiaf.org )
JavaScript
87
star
13

spm

spm • Scala Package Manager - it's based on sbt but npm-like :trollface:
Shell
79
star
14

influxdb-cli

SQL CLI for InfluxDB
JavaScript
70
star
15

common-env

🔑 The only configuration library you will ever need
JavaScript
70
star
16

sql-convention

👌 The only SQL conventions you will ever need
57
star
17

google-spreadsheet-cli

📊 CLI for reading and writing data into Google Spreadsheet
JavaScript
52
star
18

node-truncate

🐙 Truncate text and keeps urls safe.
JavaScript
52
star
19

network-config

Network configuration for NodeJS
JavaScript
50
star
20

spotify-downloader

A proof-of-concept that transforms a Spotify playlist to a direct-download list
JavaScript
50
star
21

stripe-schema

Complete Stripe (🥰) schema (as of 2019-10-09): for learning and inspiration.
Shell
34
star
22

xobject-observe

🔬 A cross-browser object property observer using ES6 proxy with a fallback on dirty-checking.
JavaScript
33
star
23

if-exp

🎩 Conditional expressions for JavaScript
JavaScript
32
star
24

postgresql-to-amqp

PostgreSQL to AMQP, forward PostgreSQL notifications to an AMQP queue.
Rust
30
star
25

node-amqp-tool

AMQP-tool - Import & export data from/to an AMQP/RabbitMQ broker
JavaScript
26
star
26

kubectx-rs

Switch between Kubernetes contexts 🏎
Shell
25
star
27

pound

Pound - High-level asset Manager for Node.js/Express
JavaScript
25
star
28

alfred-crates

Workflow for searching Rust crates from Alfred
Rust
21
star
29

jsobjectdiff

Ensure that two JavaScript files containing objects have the same keys and display differences
JavaScript
21
star
30

node-children

Concurrent tasks computation among NodeJS child processes (vertical scaling)
JavaScript
20
star
31

npm-interactive-scripts

⚡️Fast Interactive CLI for npm scripts
JavaScript
18
star
32

stripe-update-card

💳 Expose a page that let your customers update their payment information on Stripe.
Rust
18
star
33

redis-tool

Redis-tool - Little helpers for Redis
JavaScript
17
star
34

json-schema-documentation

JSON-Schema documentor (generator, cli, themes)
JavaScript
16
star
35

Growl-Chrome-Notification

Notifications Growl pour Google Chrome :: Proof of concept :: HTML5 Web Notification API + WebSocket + NodeJS
JavaScript
16
star
36

mixpanel_export_people

Export Mixpanel people properties to an Excel Compatible CSV
JavaScript
16
star
37

node-tolerant-url-parser

Overly tolerant url parser specialized in parsing protocol, auth (even invalid ones), host and port url parts.
JavaScript
15
star
38

droplr-backup

How to backup your droplr account
JavaScript
15
star
39

stream-valve

🔐 Ensure that a stream disconnects if it goes over `maxBytes` `perSeconds`
JavaScript
14
star
40

filesync

👥 Unidirectional 1-N file syncing with history and local merging
JavaScript
14
star
41

redistree

RedisTree - load & save Trees to Redis using sets
JavaScript
13
star
42

node-redis-info

Redis info string parser for NodeJS
JavaScript
13
star
43

request-api

NodeJS request library as HTTP API
JavaScript
13
star
44

amqp-replay

📹 Replay messages from (RabbitMQ) AMQP dead-letter queue
JavaScript
12
star
45

this-is-your-life

This if your life
JavaScript
12
star
46

rss-to-amp-stories

RSS to AMP Stories ⚡️
HTML
12
star
47

latenize

NPM/NodeJS port of Semplice latenize
JavaScript
12
star
48

smtp-to-sendgrid-gateway

Forward emails from SMTP requests to the Sendgrid API. Useful when the cloud provider does not allow outbound connections on ports 25, 465, 587.
JavaScript
11
star
49

my-first-nodejs-service

🐾 Workshop my first nodejs service
JavaScript
11
star
50

node-transacemail

Transactional Email & Templated Email for NodeJS done right
JavaScript
11
star
51

stargazerz

Stargazerz - export repository 🌟 stargazers 🌟 profile as JSON
JavaScript
9
star
52

kubectx

Fastest switch between #Kubernetes contexts 🏎
JavaScript
9
star
53

mixpanel-cli

🎩 mixpanel-cli - A complete CLI to query Mixpanel API
JavaScript
9
star
54

stripe-integration

Easiest Stripe Integration (ever)
Rust
9
star
55

rss-to-lametric

Your favorite RSS feed directly from your LaMetric 🎩
Rust
8
star
56

tumblr-analysis

Extract every tumblr posts as JSON from a blog and analyze them.
JavaScript
8
star
57

node-amqp-dsl

AMQP-DSL is a fluent interface for AMQP (RabbitMQ,...) on NodeJS
CoffeeScript
8
star
58

123PeopleRemover-proxy

Proxy pour 123PeoplerRemover à installer sur votre serveur
PHP
8
star
59

jQuery-plugin-attributeObserver

jQuery plugin for observing html element's property changes
JavaScript
8
star
60

node-nice-console

Patch NodeJS console methods in order to add timestamp information
JavaScript
8
star
61

gcloud

Google Cloud API client for Rust
Rust
8
star
62

jQuery-plugin-fireEvent

jQuery FireEvent - Plugin for firing real DOM events
JavaScript
8
star
63

node-ast-inlining

Node Ast Inlining is a small (~200 LOC) library that inline and expand function call
JavaScript
7
star
64

jQuery-plugin-getPath

jQuert getPath - Find a (possible) jQuery selector of an HTML element.
JavaScript
7
star
65

preg_replace---preg_replace_callback-in-javascript

PHP functions preg_replace & preg_replace_callback javascript equivalent
JavaScript
7
star
66

node-x509-certificate

Retrieve the public TLS certificate in x509 format from a distant host
JavaScript
7
star
67

lool

:trollface: Infinitely recursive self-installing useless package.
6
star
68

querystring

🦄 Querystring for Rust
Rust
5
star
69

twitterremover

How I "hijacked" Topsy private search api to remove my first 5000+ tweets
JavaScript
5
star
70

scaleway-api-client

☁ Scaleway NodeJS API Client 🚀
JavaScript
5
star
71

self-worth

See jeffreybaird/self-worth
Ruby
5
star
72

jscs2doc

🎊 Convert .jscsrc (javascript code-style configuration) to a human readable format
JavaScript
5
star
73

rk

Original idea by @stockholmux in Dancing around strings in Node.js and Redis
JavaScript
5
star
74

json-combine

Generate every possible combination of values
JavaScript
4
star
75

backbone-cappedcollection

Capped Collections for BackboneJS
JavaScript
4
star
76

Trickle-clone

A Quick & Dirty trickle clone
JavaScript
4
star
77

valid-json-template

Use a (valid) JSON as a template that produce another valid JSON as a result
JavaScript
4
star
78

chrome-freeze-tab-title

Freeze Tab Title & Favicon Chrome Extension - Increase productivity & Reduce procrastination 🌟🌟
JavaScript
4
star
79

terraform-workspace-switcher

Fastest switch between Terraform workspaces
Shell
4
star
80

clipboard-watcher

Listen to clipboard change (OSX only)
JavaScript
4
star
81

bmw_oss_dvd

♣️ BMW Open Source Software (OSS) DVD - I received for my BMW X3
3
star
82

big-brother

Web2Day Hackathon 2011
JavaScript
3
star
83

JSCSSP

JSCSSP without DOM pollution
JavaScript
3
star
84

join-events

▶️ Join events stream compatible with event emitter
JavaScript
3
star
85

app-demonstrator

Proof of Concept - (iPhone & co) Application demonstrator
JavaScript
3
star
86

postgrest-patch-request-trigger

How PostgreSQL triggers works when called with a PostgREST PATCH HTTP request
PLpgSQL
3
star
87

hostname-is-private

:squirrel: Check whether or not an hostname refers to a private IP
JavaScript
3
star
88

url-is-private

Check whether or not an url refer to a private IP
JavaScript
3
star
89

maintainers-convention

💂‍♂️ Ensure a MAINTAINERS file exist inside every repository of a Github Organisation
JavaScript
3
star
90

node-asynccallguard

Make all calls to a function queued and asynchronously guarded
JavaScript
3
star
91

ai-rom

TP cours d'IA
C
2
star
92

cancelable

Cancelable JavaScript functions
JavaScript
2
star
93

request-when

Request + WhenJS
JavaScript
2
star
94

elasticsearch-exceptions

Parse Elasticsearch exception responses and transform them into JavaScript Errors
JavaScript
2
star
95

ai-GeneticAlgorithm

Genetical Algorithm w/ Chessboard
C
2
star
96

sync-to-gitlab

👨‍🚒 Sync/backup entire directories to personal Gitlab projects
Shell
2
star
97

stretchtext

StretchText
JavaScript
2
star
98

iPhone-Particles

Simple iPhone Particles App
JavaScript
2
star
99

docker-jenkins-slave

💪 Run a Jenkins slave in docker AND access to docker cli from jobs
2
star
100

node-transacemail-mandrill

Mandrill mailProvider for node-transacemail
JavaScript
2
star