redp
Red Phosphorus - Patter Match Library for ES2015 Era
example
// create function to calculate expression treeconst calc = match // -100 + 200 ==> 100console
You could be look for more examples in example/ and test/.
install
$ npm install --save redp
API
match(value, pattern)
Shortcut to match.fn(pattern)(value)
.
match.fn(patterns)
Create new function to match patterns
. patterns
should be an Object
. Its keys should be created by when
function. Returned function accept one argument then try to match patterns
. Matching some pattern, return it. If not, return undefined
.
when(pattern)
Create pattern key from pattern
. pattern
is either some javascript value ("string"
or true
or /regexp/
or (arrow) => func
or ...) or Pattern.*
function's result. If pattern
is some javascript value, it is passed to Pattern.from
.
Pattern key is not reusable. If you want to reuse pattern
, you could use Pattern.from
.
when.and(...patterns)
Shortcut to when(Pattern.and(...patterns))
.
when.or(...patterns)
Shortcut to when(Pattern.or(...patterns))
.
Pattern
This is a factory for pattern object.
const Pattern = // Wild card pattern. It can match all values. _: ... // Rest pattern. It can match no items or some rest items of array (cannot object!). rest: ... // Create pattern object from `object`. { // If `object` is pattern object already, return `object`. // If `object` is a `RegExp`, create regexp pattern. // If `object` is an `Array`, create array pattern. // If `object` is a javascript object, create object pattern. // If `object` is a function, create condition pattern. // Otherwise, create value pattern. ... } // Create regexp pattern. { ... } // Create array pattern. { ... } // Create object pattern. { ... } // Create condition pattern. { ... } // Create value pattern. { ... } // Create 'and' pattern. { ... } // Create 'or' pattern. { ... } // If `object` is pattern object, return `true`, // otherwise return `false`. { ... }
note
This library uses ES2015 Symbol
and Map
. If you want to run this on not ES2015 environment, you can try to use some polyfills. (However, it is not tested. I'm waiting your pull-request)
license
MIT License: http://makenowjust.mit-license.org/2016
(C) 2016 TSUYUSATO Kitsune