Overview

pamatcher is a pattern matching library for JavaScript iterators that generalizes the notion of regular expression to any sequence of items of any type. Instead strings, you can use any iterable or iterator as input. Instead of characters you can use any predicate as item matcher. So you can do pattern matching in a general and declarative way.

Installation and usage

You can install pamatcher using npm:

This is an example of use:

In the example, the pattern is simple: match a number lesser than 10, followed by zero or more even numbers and finally a number greater than 10. You test an array and it should print "Pattern matches!".

If you want to use pamatcher from browser, you can use jspm. Here you have a complete pamatcher demo for browser at gist (or live at bl.ocks.org).

API

pamatcher(expression)

This is a function that transforms a pattern expression into a matcher. This is the only thing you need to import/require to use pamatcher library.

A pattern expression is a JavaScript object that specify the pattern you want to use. You can add name property to any pattern expreession in order to capture a group.

A pattern expression can be:

{ predicate: [function] }

[function]

A is a function that takes an input item, evaluates it and return a boolean. True means "item accepted".

If you pass a function as pattern expression, pamatcher will convert it to a predicate pattern expression for you.

{ value: [whatever] }

[whatever]

This is a shortcut for a (deep) equality predicate.

If you pass a value as pattern expression and that value is not an object that looks like a pattern expression, a function or an array, then pamatcher will convert it to a value pattern expression for you.

{ sequence: [array of expressions] }

[array of expressions]

A sequence of expressions. It's something like this regex: /abc/

If you pass an array as pattern expression, pamatcher will convert it to a sequence pattern expression for you.

{ or: [array of expressions] }

Logical or of multiple expressions. It's something like this regex: /(a|b|c)/

{ optional: [expression] }

An optional expression. It's something like this regex: /a?/

{ repeat: [expression] }

A sequence of zero or more expressions repeated. It's something like this regex: /a*/

{ repeat: [expression], min: [int], max: [int] }

A sequence from min up to max expressions repeated. min and max are optional. It's something like this regex: /a{2,5}/

matcher object

A matcher object can check if your expression matches to an input and capture named groups.

matcher.test(input)

The input is an iterator or an iterable. These are ES6 features. Array, String, Map, Set are iterables.

test method returns true if your pattern expression matchs your input, otherwise it returns false.

matcher.match(input)

matcher method returns an object that contains captured values of each named group.

matcher.exec(input)

exec method returns an object that contains two properties:

TODO