{"id":26502822,"url":"https://github.com/grassator/pama","last_synced_at":"2025-03-20T18:35:38.955Z","repository":{"id":57318427,"uuid":"84989261","full_name":"grassator/pama","owner":"grassator","description":"Pattern Matching for JavaScript","archived":false,"fork":false,"pushed_at":"2017-05-30T17:33:06.000Z","size":61,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-11T09:25:26.010Z","etag":null,"topics":["javascript","js","pattern-matching"],"latest_commit_sha":null,"homepage":null,"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/grassator.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-14T19:31:43.000Z","updated_at":"2020-03-31T13:45:19.000Z","dependencies_parsed_at":"2022-08-25T22:41:57.053Z","dependency_job_id":null,"html_url":"https://github.com/grassator/pama","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grassator%2Fpama","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grassator%2Fpama/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grassator%2Fpama/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/grassator%2Fpama/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/grassator","download_url":"https://codeload.github.com/grassator/pama/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244671870,"owners_count":20491269,"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","js","pattern-matching"],"created_at":"2025-03-20T18:35:38.186Z","updated_at":"2025-03-20T18:35:38.939Z","avatar_url":"https://github.com/grassator.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pama\n\n[![NPM version](https://badge.fury.io/js/pama.svg)](https://npmjs.org/package/pama)\n[![Build Status][travis-image]][travis-url]\n\n[project-url]: https://github.com/grassator/pama\n[travis-url]: https://travis-ci.org/grassator/pama\n[travis-image]: https://travis-ci.org/grassator/pama.svg?branch=master\n\n`pama` is a library that introduces the concept of pattern matching to JavaScript. While some similar libraries exist (e.g. [funcy](https://www.npmjs.com/package/funcy) and [matches.js](https://github.com/natefaubion/matches.js)), they fail to match all of the goals set for `pama`:\n\n1. Nested matching and capturing of values.\n2. Consistent API implemented in JS without a custom DSL.\n3. Minimal footprint both in terms of size and performance.\n4. Support for guards.\n\n## Quick Setup\n\nAdd the library to your project using yarn:\n\n```\nyarn add -D pama\n```\n\nor NPM:\n\n```\nnpm install -D pama\n```\n\nThen import it into your project:\n\n```js\nimport {when, is} from 'pama';\n```\n\nHere's how you can check for a specific number, string or anything else:\n\n```js\nconst foo = when(valueToMatch, (_, x) =\u003e\n    is(42)       ? 'The Answer!' :\n    is('string', _) ? x.length :\n    /* otherwise */ 'dunno'\n);\n```\n\nAn important difference of `when` function vs `switch` is that it returns the result\nof the matched branch, which makes writing functional-style code easier.\n\nAnother thing to keep in mind is that the order of branches is important.\n\n## Syntax definition\n\n```js\nwhen(value, (_, sameValue) =\u003e\n    is(pattern) ? nonFunctionValueOrCallback :\n    is(type, _) ? nonFunctionValueOrCallback :\n    is(type, pattern) ? nonFunctionValueOrCallback :\n    otherwiseBranch\n);\n```\n\n* `value` (optional) — value that is going to be matched. If this argument is not present,\nthe return value of `when` call will be a function expecting one argument and returning the same\nargument, so `when(() =\u003e ...` is same as `value =\u003e when(value, () =\u003e ...`.\n\n* `_` — this is a special value that when used inside of an `is` matcher,\nwill match anything. It is named `_` for shortness and similarity with functional languages like\nHaskell.\n\n* `sameValue` - the same `value` that was passed to `when` as a first argument. This a necessity\nfor cases of using `when` to create a function, but allows you to provide a different name for\nthe value you are matching on, which is handy when the original one is too verbose.\n\n* The body of the callback is just an ordinary [conditional expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator.html).\nThe only extra functionality provided is in the implementation of `is` and how the return value\nof the callback is treated.\n\n* `is` — this function accept a `pattern`, or a `type` and a `pattern`, and returns `true` if\nthe `value` is matching the pattern. [Tests file](https://github.com/grassator/pama/master/index.test.js) has a full list of the supported patterns and types.\n\n* `nonFunctionValueOrCallback` — if this is a function, it's treated as a \"match callback\" and gets\nthe original `value` as it's only argument, for all other JS types, the value here will be the return value of `when` in case of a match.\n\n* `otherwiseBranch` - since `pama` (ab)uses conditional expressions, you always have to have a final\n\"else\" branch that is taken when nothing matched. If you don't want to return anything, the convention\nis to put `undefined` on this place.\n\n## Advanced Usage\n\n### Regular Expression\n\nIt is possible to match string values directly with regular expressions:\n\n```js\nwhen('foo', _ =\u003e\n    is(/b\\w+/) ? 'b-like' :\n    is(/f\\w+/) ? 'f-like' :\n    undefined\n); // returns 'f-like'\n```\n\n\u003e one thing to note is that unlike regular someRegexp.test(), this check does not coerce the type to string, so if\nprovided value is not a string, it will automatically doesn't match this branch. \n\n### Guards\n\n\u003e *Guard* is an additional condition on top of a declarative match that allows to further refine the match.\n\nSince `pama` just expects the predicate to return a boolean value, you can add arbitrary conditions in\nthe same manner as you would with a regular `if` statement:\n\n\n```js\nwhen(value, (_, x) =\u003e\n    is(0)                    ? 'zero'     :\n    is('number', _) \u0026\u0026 x \u003e 0 ? 'positive' :\n    is('number', _) \u0026\u0026 x \u003c 0 ? 'negative' :\n    'not a number'\n);\n```\n\nIf you have performance concerns, or don't want to repeat yourself it's possible to use the\nflexibility of JS to your advantage:\n\n```js\nwhen(valueToMatch, (_, x, g) =\u003e\n    (g = is({ foo: 'bar', num: _ })) \u0026\u0026\n        g \u0026\u0026 x.num \u003e 0 ? 'positive' :\n        g \u0026\u0026 x \u003c 0     ? 'negative' :\n    'not a number'\n);\n```\n\n### Deep Matching\n\n```js\nconst a = {foo: {foo:{foo: 'bar'}}};\n\nwhen(a, _ =\u003e\n    is({foo: 'foo'}) ? 'foo' :\n    is({foo: {foo:{foo: 'bar'}}}) ? 'bar' :\n    undefined\n); // returns 'bar'\n```\n\n## Corner Cases\n\nWhen designing `pama` I had to make a decision on either being always very verbose,\nor having a more concise syntax for common situations, but have some corner cases.\n\nThere are just a few corner cases I could identify, and they are described below:\n\n### Matching on functions\n\nSince functions also act as custom predicates, this will not work:\n\n```js\nconst f = () =\u003e {};\nwhen(f, () =\u003e\n    is(f) ? 'yes' :\n    'no'\n); // returns 'no'\n```\n\nBut it works when you provide the type explicitly:\n\n```js\nconst f = () =\u003e {};\nwhen(f, () =\u003e\n    is('function', f) ? 'yes' :\n    'no'\n); // returns 'yes'\n```\n\nOr you can also just compare yourself:\n\n```js\nconst f1 = () =\u003e {};\nconst f2 = () =\u003e {};\nwhen(f1, (_, x) =\u003e\n    x === f1 ? 'f1' :\n    x === f2 ? 'f2' :\n    'no'\n); // returns 'f2'\n```\n\n### Returning a function from a match\n\nJust putting a function into a match won't work, as it is considered to be a callback for that match:\n\n```js\nconst expectedReturn = () =\u003e 42;\nwhen(true, (_, x) =\u003e\n    true ? expectedReturn :\n    undefined\n); // calls `expectedReturn` and returns the result (42)\n```\n\nIf you wish to return a function from a match, you need to wrap it in an anonymous function:\n\n```js\nconst expectedReturn = () =\u003e 42;\nwhen(true, (_, x) =\u003e\n    true ? () =\u003e expectedReturn :\n    undefined\n); // returns expectedReturn\n```\n\n### Array and Object type matching\n\nSince every window (or iframe) in the browser gets a fresh set of globals, this code will not work:\n\n```js\nwhen(arrayComingFromAnotherWindow, () =\u003e\n    is(Array) ? 'array' :\n    'not an array'\n);\n```\n\nInstead, if you have to support objects coming from another contexts, you have to use\nslightly more awkward version: \n\n```js\nwhen(arrayComingFromAnotherWindow, () =\u003e\n    is(Array.isArray) ? 'array' :\n    'not an array'\n);\n```\n\n`Object` global has the same problem, but for it you can always use this format:\n\n```js\nwhen(objectComingFromAnotherWindow, _ =\u003e\n    is('object', _) ? 'object' :\n    'not an object'\n); // will return 'object', as expected\n```\n\n## Browser / Environment Support\n\n* Evergreen (Chrome, Firefox, Opera, Safari, Edge)\n* IE9+\n* Node.js 0.10\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2017 Dmitriy Kubyshkin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrassator%2Fpama","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgrassator%2Fpama","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgrassator%2Fpama/lists"}