Skip to content

Commit

Permalink
Add the matches pattern helper
Browse files Browse the repository at this point in the history
  • Loading branch information
bas080 committed Oct 5, 2022
1 parent 554ee2b commit 249eba6
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
27 changes: 27 additions & 0 deletions README.mz
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ npm install patroon
```js node -
const {

// Match Helpers
patroon,
matches,

// Pattern Helpers
every,
Expand Down Expand Up @@ -392,6 +394,31 @@ patroon(
)([{a: 43}])
```

### Matches

A pattern matching helper that can help with using patroon patterns in if
statements and such.

```js ./tape-test
const isUser = matches({user: _})
const isAdmin = matches({user: {admin: true}})

const user = {
user: {
id: 2
}
}

const admin = {
user: {
id: 1,
admin: true
}
}

JSON.stringify([isUser(admin), isUser(user), isAdmin(admin), isAdmin(user)])
```

### Custom Helper

It is very easy to write your own helpers. All the builtin helpers are really
Expand Down
8 changes: 8 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ function instanceOf (ctor) {
return value => value instanceof ctor
}

function matches (pattern) {
return patroon(
pattern, true,
T, false
)
}

module.exports = Object.assign(patroon, {
NoMatchError,
UnevenArgumentCountError,
Expand All @@ -121,5 +128,6 @@ module.exports = Object.assign(patroon, {
typed,
t: typed,
instanceOf,
matches,
_: T
})
21 changes: 21 additions & 0 deletions src/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { version } = require('../package')
const {
reference,
instanceOf,
matches,
typed,
t,
ref,
Expand Down Expand Up @@ -227,6 +228,26 @@ test('Does not match on reference', t => {
t.end()
})

test('Matches function', check(gen.any, gen.any, (t, a, b) => {
t.ok(matches(a)(a))
t.equals(typeof matches(a)(b), 'boolean')
t.end()
}))

test('Check that matches throws non patroon errors', t => {
class SomeError extends Error { }

const predicate = () => {
throw new SomeError()
}
const pattern = {
predicate
}

t.throws(() => matches(pattern)({ predicate: 2 }), SomeError)
t.end()
})

if (version.startsWith('2')) {
test('Deprecated functions in version 2', t => {
t.plan(3)
Expand Down
1 change: 1 addition & 0 deletions tape-test
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ cat <(echo '
const {
_,
every,
matches,
instanceOf,
some,
multi,
Expand Down

0 comments on commit 249eba6

Please sign in to comment.