A pattern-matching DSL for JSON-like trees of data.
pattern. If the match succeeds, the result is a sub-match object,
which consists of the sub-components of the value that matched named
sub-patterns (using the
var pattern). If the match fails, a
MatchError is thrown.
Here's a simple example of using pattern matching to analyze an AST for a hypothetical language:
var match = require'pattern-match';matchastwhentype: 'FunctionCall'callee: matchvar'callee'args: matchvar'args'thisanalyzeFunctionCallvarscallee varsargs;this;whentype: 'Assignment'lhs: matchvar'lhs'rhs: matchvar'rhs'thisanalyzeAssignmentvarslhs varsrhs;this;whentype: 'Return'arg: matchvar'arg'thisanalyzeReturnvarsarg;this;this;
This will get sweeter in ES6 with destructuring:
var match = require'pattern-match';matchastwhentype: 'FunctionCall'callee: matchvar'callee'args: matchvar'args'thisanalyzeFunctionCallcallee args;this;whentype: 'Assignment'lhs: matchvar'lhs'rhs: matchvar'rhs'thisanalyzeAssignmentlhs rhs;this;whentype: 'Return'arg: matchvar'arg'thisanalyzeReturnarg;this;this;
And sweeter still with ES6 arrow-functions:
var match = require'pattern-match';matchast when =>whentype: 'FunctionCall'callee: matchvar'callee'args: matchvar'args'callee args =>thisanalyzeFunctionCallcallee args;;whentype: 'Assignment'lhs: matchvar'lhs'rhs: matchvar'rhs'lhs rhs =>thisanalyzeAssignmentlhs rhs;;whentype: 'Return'arg: matchvar'arg'arg =>thisanalyzeReturnarg;;;
x against a sequence of patterns, returning the result of the
first successful match. The cases are provided by the
Provides the cases by calling
when in the order the cases should be
Provides the next case, consisting of a pattern an optional
template. If matching the pattern succeeds, the result is passed to
thisArg bound to
this (defaults to the global
template is not provided, this case produces the
x against a single pattern. Returns the result of calling
template on the sub-match object with
thisArg (or the global
object by default) as the binding of
template is not
provided, returns the sub-match object.
any) and saves the value in the sub-match object with property name
predreturns a truthy value.
patternn, respectively. Only the own properties of the pattern are used.
You can create custom patterns by extending the root pattern prototype.
Errorthat represents a failed pattern-match.