import match, when, otherwise from 'match-iz' match(haystack)( when(needle)(true), when(thread)(false), otherwise('bale') )
Essentially, pattern-matching is if/then and switch/case with a little more declarative cowbell. 🐮 🔔
We can probe into an object:
const todosReducer = (state, action) => match(action)( when( type: 'set-vis-filter' ) (( visFilter ) => ( ...state, visFilter )), when( type: 'add-todo' ) (( text ) => ( ...state, todos: [...state.todos, text, completed: false ] )), otherwise(state) )
…test against predicates as well as literals:
const defined = obj => !!obj function AccountPage(props) return match(props)( when( error: true )(<Error ...props />), when( loading: true )(<Loading />), when( data: defined )(<Page ...props />), otherwise(<Logout />) )
…which is handy for dealing with server-responses:
const getJsonLength = async () => match(await fetch('/json'))( when( status: 200 ) (( headers: 'Content-Length': s = ) => return `size is $s` ), when(( status ) => status >= 500)('Server error!'), when( status: 404 )('JSON not found'), when( status: gte(400) )('Flagrant error!'), otherwise("I didn't understand that...") )
…and match strings against regular-expressions, passing the result into the handler:
match('1 + 2')( when(/(?<left>d+) + (?<right>d+)/) (( groups: left, right ) => add(left, right) ), when(/(?<left>d+) - (?<right>d+)/) (( groups: left, right ) => subtract(left, right) ), otherwise("I couldn't parse that!") ) // 3
The only thing we can’t have is
else instead of
The full TC39 proposal is more far-reaching because it is inspired by the advanced pattern-matching features offered by functional languages with mature implementations.
It’s not a substitute for well named intermediate variables of course, but I hope you can see its utility.