README
pmatch
Pmatch is yet another attempt to make pattern matching a thing in javascript. The concept of argument pattern matching comes from Haskell.
map _ [] = []
map f (x:xs) = f x : map f xs
The idea is to match the patterns of arguments passed to a function to handle different cases in different function.
Not many pattern features are added and there might be 🐲
usage
const fn = pmatch()
.when('foo', () => 'it\'s foo')
.when('bar', () => 'it\'s bar')
.when(() => 'it\'s something else')
fn('foo') // it's foo
fn('bar') // it's bar
fn('baz') // it's something else
Pmatch will attempt to match the correct argument pattern and call the correct function.
const map = pmatch()
.when('*', [], () => [])
.when(() => {}, (f, a) => {
return [f(a[0])].concat(map(f, a.slice(1)))
})
map(x => x * 10, [10, 20]) // [100, 200]
shallow compares
pmatch has shallow compares to allow for matching in objects and arrays.
const reducer = pmatch()
.when('*', {type: 'SET'}, (state, {key, value}) => {
return Object.assign({}, state, {[key]: value})
})
.when('*', {type: 'UNSET'}, (state, {key}) => {
return Object.assign({}, state, {[key]: null})
})
.when('*', {type: 'RESET'}, () => Object.assign({}, initialState))
.when((state = initialState) => state)