{"id":22473117,"url":"https://github.com/bas080/patroon","last_synced_at":"2025-08-02T10:30:59.184Z","repository":{"id":45655738,"uuid":"333962091","full_name":"bas080/patroon","owner":"bas080","description":"Programmatic pattern matching in Javascript without additional syntax.","archived":false,"fork":false,"pushed_at":"2023-10-09T23:47:49.000Z","size":323,"stargazers_count":5,"open_issues_count":5,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-11-24T01:34:09.755Z","etag":null,"topics":["javascript","pattern-matching"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/patroon","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bas080.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-28T21:33:17.000Z","updated_at":"2023-10-09T05:58:36.000Z","dependencies_parsed_at":"2024-10-23T12:11:06.924Z","dependency_job_id":null,"html_url":"https://github.com/bas080/patroon","commit_stats":{"total_commits":85,"total_committers":1,"mean_commits":85.0,"dds":0.0,"last_synced_commit":"49369653b95463e1b700f265c11a61d150634b55"},"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fpatroon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fpatroon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fpatroon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bas080%2Fpatroon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bas080","download_url":"https://codeload.github.com/bas080/patroon/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228124670,"owners_count":17873168,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","pattern-matching"],"created_at":"2024-12-06T12:19:06.787Z","updated_at":"2024-12-06T12:19:09.180Z","avatar_url":"https://github.com/bas080.png","language":"JavaScript","readme":"# Patroon\n\nPattern matching in JavaScript without additional syntax.\n\n[![NPM](https://img.shields.io/npm/v/patroon?color=blue\u0026style=flat-square)](https://www.npmjs.com/package/patroon)\n[![NPM Downloads](https://img.shields.io/npm/dm/patroon?style=flat-square)](https://www.npmjs.com/package/patroon)\n[![100% Code Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square)](#tests)\n[![Standard Code Style](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](https://standardjs.com)\n[![License](https://img.shields.io/npm/l/patroon?color=brightgreen\u0026style=flat-square)](./LICENSE)\n\n- [Installation](#installation)\n- [Usage](#usage)\n  * [Primitive](#primitive)\n  * [Regular Expression](#regular-expression)\n  * [Placeholder](#placeholder)\n  * [Object](#object)\n  * [Instance](#instance)\n  * [Reference](#reference)\n  * [Array](#array)\n  * [Every](#every)\n  * [Some](#some)\n  * [Multi](#multi)\n  * [Predicate](#predicate)\n  * [Matches](#matches)\n  * [Custom Helper](#custom-helper)\n  * [Errors](#errors)\n    + [NoMatchError](#nomatcherror)\n    + [UnevenArgumentCountError](#unevenargumentcounterror)\n    + [PatroonError](#patroonerror)\n- [Examples](#examples)\n- [Tests](#tests)\n- [Changelog](#changelog)\n- [Contribute](#contribute)\n  * [Contributors](#contributors)\n\n## Installation\n\n[Patroon][9] is hosted on the NPM repository.\n\n```bash\nnpm install patroon\n```\n\n## Usage\n\n```js\nconst {\n\n  // Match Helpers\n  patroon,\n  matches,\n\n  // Pattern Helpers\n  every,\n  some,\n  multi,\n  reference,\n  instanceOf,\n  _,\n\n  // Errors\n  NoMatchError,\n  UnevenArgumentCountError,\n  PatroonError,\n} = require('patroon')\n```\n\nLet's see what valid and less valid uses of patroon are.\n\n\u003e You can try out patroon over at [RunKit][runkit].\n\n### Primitive\n\nThe simplest thing one can do is to match on a [primitive][1].\n\nNumbers:\n\n```js\npatroon(\n  2, 3,\n  1, 2\n)(1)\n```\n```\n2\n```\n\nStrings:\n\n```js\npatroon(\n  'a', 'b',\n  'c', 'd'\n)('c')\n```\n```\nd\n```\n\nBooleans:\n\n```js\npatroon(\n  true, false,\n  false, true\n)(true)\n```\n```\nfalse\n```\n\nSymbols:\n\n```js\nconst a = Symbol('a')\nconst b = Symbol('b')\nconst c = Symbol('c')\n\npatroon(\n  a, b,\n  b, c\n)(b)\n```\n```\nSymbol(c)\n```\n\nNil values:\n\n```js\npatroon(\n  null, undefined,\n  undefined, null,\n)(undefined)\n```\n```\nnull\n```\n\n### Regular Expression\n\nWill check if a Regex matches the passed string using the string's `.test`\nmethod.\n\n```js\npatroon(\n  /^bunion/, 'string starts with bunion',\n  /^banana/, 'string starts with banana'\n)('banana tree')\n```\n```\nstring starts with banana\n```\n\n### Placeholder\n\nThe `_` is a placeholder/wildcard value that is useful to implement a default case.\n\n```js\npatroon(\n  1, 'value is 1',\n  'a', 'value is a',\n  _, 'value is something else'\n)(true)\n```\n```\nvalue is something else\n```\n\nWe can combine the `_` with other patroon features.\n\n### Object\n\nPatroon can help you match **objects** that follow a certain spec.\n\n```js\npatroon(\n  {b: _}, 'has a \"b\" property',\n  {a: _}, 'has an \"a\" property'\n)({b: 2})\n```\n```\nhas a \"b\" property\n```\n\nNext we also match on the key's value.\n\n```js\npatroon(\n  {a: 1}, 'a is 1',\n  {a: 2}, 'a is 2',\n  {a: 3}, 'a is 3'\n)({a: 2})\n```\n```\na is 2\n```\n\nWhat about nested objects?\n\n```js\npatroon(\n  {a: {a: 1}}, 'a.a is 1',\n  {a: {a: 2}}, 'a.a is 2',\n  {a: {a: 3}}, 'a.a is 3'\n)({a: {a: 2}})\n```\n```\na.a is 2\n```\n\n### Instance\n\nSometimes it's nice to know if the value is of a certain type. We'll use the\nbuiltin node error constructors in this example.\n\n```js\npatroon(\n  instanceOf(TypeError), 'is a type error',\n  instanceOf(Error), 'is an error'\n)(new Error())\n```\n```\nis an error\n```\n\nPatroon uses `instanceof` to match on types.\n\n```js\nnew TypeError() instanceof Error\n```\n```\ntrue\n```\n\nBecause of this you can match a TypeError with an Error.\n\n```js\npatroon(\n  instanceOf(Error), 'matches on error',\n  instanceOf(TypeError), 'matches on type error'\n)(new TypeError())\n```\n```\nmatches on error\n```\n\nAn object of a certain type might also have values we would want to match on.\nHere you should use the every helper.\n\n```js\npatroon(\n  every(instanceOf(TypeError), { value: 20 }), 'type error where value is 20',\n  every(instanceOf(Error), { value: 30 }), 'error where value is 30',\n  every(instanceOf(Error), { value: 20 }), 'error where value is 20'\n)(Object.assign(new TypeError(), { value: 20 }))\n```\n```\ntype error where value is 20\n```\n\nMatching on an object type can be written in several ways.\n\n```js\npatroon({}, 'is object')({})\npatroon(Object, 'is object')({})\n```\n\nThese are all equivalent.\n\nArrays can also be matched in a similar way.\n\n```js\npatroon([], 'is array')([])\npatroon(Array, 'is array')([])\n```\n\nA less intuitive case:\n\n```js\npatroon({}, 'is object')([])\npatroon([], 'is array')({})\n```\n\nPatroon allows this because Arrays can have properties defined.\n\n```js\nconst array = []\narray.prop = 42\n\npatroon({prop: _}, 'has prop')(array)\n```\n\nThe other way around is also allowed even if it seems weird.\n\n```js\nconst object = {0: 42}\npatroon([42], 'has 0th')(object)\n```\n\nIf you do not desire this loose behavior you can use a predicate to make sure\nsomething is an array or object.\n\n```js\npatroon(Array.isArray, 'is array')([])\n```\n\n### Reference\n\nIf you wish to match on the reference of a constructor you can use the `ref`\nhelper.\n\n```js\npatroon(\n  instanceOf(Error), 'is an instance of Error',\n  reference(Error), 'is the Error constructor'\n)(Error)\n```\n```\nis the Error constructor\n```\n\n### Array\n\n```js\npatroon(\n  [], 'is an array',\n)([1, 2, 3])\n```\n```\nis an array\n```\n\n```js\npatroon(\n  [1], 'is an array that starts with 1',\n  [1,2], 'is an array that starts with 1 and 2',\n  [], 'is an array',\n)([1, 2])\n```\n```\nis an array that starts with 1\n```\n\n\u003e Think of patterns as a subset of the value you are trying to match. In the\n\u003e case of arrays. `[1,2]` is a subset of `[1,2,3]`. `[2,3]` is not a subset of\n\u003e `[1,2,3]` because arrays also care about the order of elements.\n\nWe can also use an object pattern to match certain indexes. The same can be\nwritten using an array pattern and the `_`. The array pattern can become a bit\nverbose when wanting to match on a bigger index.\n\nThese two patterns are equivalent:\n\n```js\npatroon(\n  {6: 7}, 'Index 6 has value 7',\n  [_, _, _, _, _, _, 7], 'Index 6 has value 7'\n)([1, 2, 3, 4, 5, 6, 7])\n```\n```\nIndex 6 has value 7\n```\n\nA function that returns the lenght of an array:\n\n```js\nconst count = patroon(\n  [_], ([, ...xs]) =\u003e 1 + count(xs),\n  [], 0\n)\n\ncount([0,1,2,3])\n```\n```\n4\n```\n\nA function that looks for a certain pattern in an array:\n\n```js\nconst containsPattern = patroon(\n  [0, 0], true,\n  [_, _], ([, ...rest]) =\u003e containsPattern(rest),\n  [], false\n)\n\ncontainsPattern([1,0,1,0,0])\n```\n```\ntrue\n```\n\nA toPairs function:\n\n```js\nconst toPairs = patroon(\n  [_, _], ([a, b, ...c], p = []) =\u003e toPairs(c, [...p, [a, b]]),\n  _, (_, p = []) =\u003e p\n)\n\ntoPairs([1, 2, 3, 4])\n```\n```\n[ [ 1, 2 ], [ 3, 4 ] ]\n```\n\n\u003e An exercise would be to change toPairs to throw when an uneven length array\n\u003e is passed. Multiple answers are possible and some are more optimized than\n\u003e others.\n\n### Every\n\nA helper that makes it easy to check if a value passes all patterns.\n\n```js\nconst gte200 = x =\u003e x \u003e= 200\nconst lt300 = x =\u003e x \u003c 300\n\npatroon(\n  every(gte200, lt300), 'Is a 200 status code'\n)(200)\n```\n```\nIs a 200 status code\n```\n\n### Some\n\nA helper to check if any of the pattern matches value.\n\n```js\nconst isMovedResponse = patroon(\n  {statusCode: some(301, 302, 307, 308)}, true,\n  _, false\n)\n\nisMovedResponse({statusCode: 301})\n```\n```\ntrue\n```\n\n### Multi\n\nPatroon offers the `multi` function in order to match on the value of another\nargument than the first one. This is named [multiple dispatch][2].\n\n```js\n  patroon(\n    multi(1, 2, 3), 'arguments are 1, 2 and 3'\n  )(1, 2, 3)\n```\n```\narguments are 1, 2 and 3\n```\n\n### Predicate\n\nBy default a function is assumed to be a predicate.\n\nSee the [references](#references) section if you wish to match on the reference\nof the function.\n\n```js\nconst isTrue = v =\u003e v === true\n\npatroon(\n  isTrue, 'is true'\n)(true)\n```\n```\nis true\n```\n\nCould one combine predicates with arrays and objects? Sure one can!\n\n```js\nconst gt20 = v =\u003e v \u003e 20\n\npatroon(\n  [[gt20]], 'is greater than 20'\n)([[21]])\n```\n```\nis greater than 20\n```\n\n```js\nconst gt42 = v =\u003e v \u003e 42\n\npatroon(\n  [{a: gt42}], 'is greater than 42'\n)([{a: 43}])\n```\n```\nis greater than 42\n```\n\n### Matches\n\nA pattern matching helper that can help with using patroon patterns in if\nstatements and such.\n\n```js\nconst isUser = matches({user: _})\nconst isAdmin = matches({user: {admin: true}})\n\nconst user = {\n  user: {\n    id: 2\n  }\n}\n\nconst admin = {\n  user: {\n    id: 1,\n    admin: true\n  }\n}\n\nJSON.stringify([isUser(admin), isUser(user), isAdmin(admin), isAdmin(user)])\n```\n```\n[true,true,true,false]\n```\n\n### Custom Helper\n\nIt is very easy to write your own helpers. All the builtin helpers are really\njust predicates. Let's look at the source of one of these helpers, the simplest\none being the `_` helper.\n\n```js\n_.toString()\n```\n```\n() =\u003e true\n```\n\nOther more complex helpers like the `every` or `some` helper are also\npredicates.\n\n```js\nevery.toString()\n```\n```\n(...patterns) =\u003e {\n  const matches = patterns.map(predicate)\n\n  return (...args) =\u003e matches.every(pred =\u003e pred(...args))\n}\n```\n\nSee the [./src/index.js][3] if you are interested in the implementation.\n\n### Errors\n\nPatroon has errors that occur during runtime and when a patroon function is\ncreated. It's important to know when they occur.\n\n#### NoMatchError\n\nThe no match error occurs when none of the patterns match the value.\n\n```js\nconst oneIsTwo = patroon(1, 2)\n\noneIsTwo(3)\n```\n```\n/home/ant/projects/patroon/src/index.js:96\n      throw error\n      ^\n\nNoMatchError: Not able to match any pattern for arguments\n    at /home/ant/projects/patroon/src/index.js:90:21\n```\n\n#### UnevenArgumentCountError\n\nAnother error that occurs is when the patroon function is not used correctly.\n\n```js\npatroon(1)\n```\n```\n/home/ant/projects/patroon/src/index.js:82\n  if (!isEven(list.length)) { throw new UnevenArgumentCountError('Patroon should have an even amount of arguments.') }\n                              ^\n\nUnevenArgumentCountError: Patroon should have an even amount of arguments.\n    at patroon (/home/ant/projects/patroon/src/index.js:82:37)\n```\n\n#### PatroonError\n\nAll errors patroon produces can be matched against the PatroonError using `instanceof`.\n\n```js\nconst isPatroonError = patroon(instanceOf(PatroonError), 'patroon is causing an error')\n\nisPatroonError(new NoMatchError())\nisPatroonError(new UnevenArgumentCountError())\n```\n```\npatroon is causing an error\n```\n\n## Examples\n\nPatroon can be used in any context that can benefit from pattern matching.\n\n- The following tests show how patroon can help you test your JSON API by\n  pattern matching on status codes and the body:\n  https://github.com/bas080/didomi/blob/master/index.test.js.\n\n## Tests\n\n[./src/index.test.js][5] - Contains some tests for edge cases and it defines\nsome property based tests.\n\nWe also care about code coverage so we'll use [nyc][8] to generate a coverage\nreport.\n\n```bash\n# Clean install dependencies.\nnpm ci \u0026\u003e /dev/null\n\n# Run tests and generate a coverage report\nnpx nyc npm t | npx tap-nyc\n\n# Test if the coverage is 100%\nnpx nyc check-coverage\n```\n```\n    \u003e patroon@1.5.3 test\n    \u003e tape ./src/index.test.js\n    -------------|---------|----------|---------|---------|-------------------\n    File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n    -------------|---------|----------|---------|---------|-------------------\n    All files    |     100 |      100 |     100 |     100 |                   \n     helpers.js  |     100 |      100 |     100 |     100 |                   \n     index.js    |     100 |      100 |     100 |     100 |                   \n     walkable.js |     100 |      100 |     100 |     100 |                   \n    -------------|---------|----------|---------|---------|-------------------\n\n  total:     31\n  passing:   31\n\n  duration:  9.3s\n\n```\n\n## Changelog\n\nSee the [CHANGELOG.md][changelog] to know what changes are introduced for each\nversion release.\n\n## Contribute\n\nYou may contribute in whatever manner you see fit. Do try to be helpful and\npolite and read the [CONTRIBUTING.md][10].\n\n### Contributors\n\n- **Bassim Huis** *https://github.com/bas080*\n- **Scott Sauyet** *http://scott.sauyet.com*\n\n\n[1]:https://developer.mozilla.org/en-US/docs/Glossary/Primitive\n[2]:https://en.wikipedia.org/wiki/Multiple_dispatch\n[3]:https://github.com/bas080/patroon/blob/master/src/index.js\n[5]:./src/index.test.js\n[7]:https://stackoverflow.com/questions/50452844/functional-programming-style-pattern-matching-in-javascript/67376827#67376827\n[8]:https://github.com/istanbuljs/nyc\n[9]:https://www.npmjs.com/package/patroon\n[10]:./CONTRIBUTING.md\n[changelog]:./CHANGELOG.md\n[runkit]:https://npm.runkit.com/patroon\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbas080%2Fpatroon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbas080%2Fpatroon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbas080%2Fpatroon/lists"}