Once we have a matcher, there are several ways to use this matcher. Let us start with the reason for this library, pattern matching
{
const runAMatch = (someValue) =>
matches(someValue)
.when(simpleMatch, (matchedValue) => `I have matched the simple value of ${matchedValue}`)
.when(moreComplicated, ({ value, maybeValue }) => `I have matched the complicated with the value as ${value} and the maybe value as ${maybeValue}`)
.defaultTo('I couldn\'t find a value to match against');
console.log(`runAMatch('test') = ${runAMatch('test')}`)
console.log(`runAMatch({value: 'hi'}) = ${runAMatch({value: 'hi'})}`)
console.log(`runAMatch({value: 'hi', maybeValue: 'there'}) = ${runAMatch({value: 'hi', maybeValue: 'there'})}`)
}
We can use unsafeCasting (also a promise version) to ensure we are getting the correct value
console.log(`Here we have valid ${simpleMatch.unsafeCast('valid')}`);
try {
moreComplicated.unsafeCast({ value: 5 });
} catch (e) {
console.log(`And here for mismatch ${e}`)
}
Or we can get to the root by using parse
console.log(simpleMatch.parse(6, {
parsed: a => `We have value of ${a}`,
invalid: error => `We get a description of what failed: ${error.name}`
}))
And we can have maybes and defaulting to
{
const maybeMatchNumber = matches.number.optional()
const defaultMatch = matches.number.defaultTo(5)
const someSimpleValue = null // Try 5 or undefined
console.log(`Defaulting a value at later time time: ${maybeMatchNumber.unsafeCast(someSimpleValue) || 4}`)
console.log(`Defaulting a value at time: ${defaultMatch.unsafeCast(someSimpleValue)}`)
const maybeShape = matches.shape({
value: matches.string.optional()
})
console.log(`We can use a shape value: ${maybeShape.unsafeCast({value: null}).value || 4}`)
}