TS-Matches

node v14.20.1
version: 5.1.0
endpointsharetweet
This is using runkit, play with it
First we will want to include our matching library
let matches = require('ts-matches').default
Then from here we will want to create some matchers, so we will have one for a simple and one more complicated
const simpleMatch = matches.string; const moreComplicated = matches.shape({ value: matches.string, })
We can use it to test that we match a shape
{ console.log(simpleMatch.test('String here')) console.log(simpleMatch.test(4)) }
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}`) }
Loading…

no comments

    sign in to comment