From 249eba61481ce1a8899a3474c5055e85d441b783 Mon Sep 17 00:00:00 2001 From: Bas Huis Date: Thu, 6 Oct 2022 00:09:38 +0200 Subject: [PATCH] Add the matches pattern helper --- README.mz | 27 +++++++++++++++++++++++++++ src/index.js | 8 ++++++++ src/index.test.js | 21 +++++++++++++++++++++ tape-test | 1 + 4 files changed, 57 insertions(+) diff --git a/README.mz b/README.mz index c43405b..c3e211c 100644 --- a/README.mz +++ b/README.mz @@ -24,7 +24,9 @@ npm install patroon ```js node - const { + // Match Helpers patroon, + matches, // Pattern Helpers every, @@ -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 diff --git a/src/index.js b/src/index.js index 5261cc7..28bd168 100755 --- a/src/index.js +++ b/src/index.js @@ -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, @@ -121,5 +128,6 @@ module.exports = Object.assign(patroon, { typed, t: typed, instanceOf, + matches, _: T }) diff --git a/src/index.test.js b/src/index.test.js index 37c8465..9814e80 100755 --- a/src/index.test.js +++ b/src/index.test.js @@ -5,6 +5,7 @@ const { version } = require('../package') const { reference, instanceOf, + matches, typed, t, ref, @@ -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) diff --git a/tape-test b/tape-test index 5c6db24..3b88362 100755 --- a/tape-test +++ b/tape-test @@ -4,6 +4,7 @@ cat <(echo ' const { _, every, + matches, instanceOf, some, multi,