{"id":20165732,"url":"https://github.com/functionalland/functional","last_synced_at":"2025-04-10T01:02:01.386Z","repository":{"id":50621496,"uuid":"288468423","full_name":"functionalland/functional","owner":"functionalland","description":"Common Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.","archived":false,"fork":false,"pushed_at":"2021-06-10T14:01:02.000Z","size":304,"stargazers_count":111,"open_issues_count":0,"forks_count":2,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-03-24T02:43:11.408Z","etag":null,"topics":["algebraic-data-types","browser","catamorphism","category-theory","deno","denoland","either","either-monad","fold","functional","functional-programming","functor","io-monad","maybe","maybe-monad","monoid","task","task-monad"],"latest_commit_sha":null,"homepage":"","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/functionalland.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-08-18T13:48:00.000Z","updated_at":"2025-02-20T00:53:57.000Z","dependencies_parsed_at":"2022-09-26T21:31:06.464Z","dependency_job_id":null,"html_url":"https://github.com/functionalland/functional","commit_stats":null,"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/functionalland%2Ffunctional","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/functionalland%2Ffunctional/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/functionalland%2Ffunctional/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/functionalland%2Ffunctional/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/functionalland","download_url":"https://codeload.github.com/functionalland/functional/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247898511,"owners_count":21014721,"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":["algebraic-data-types","browser","catamorphism","category-theory","deno","denoland","either","either-monad","fold","functional","functional-programming","functor","io-monad","maybe","maybe-monad","monoid","task","task-monad"],"created_at":"2024-11-14T00:38:54.671Z","updated_at":"2025-04-10T01:02:01.336Z","avatar_url":"https://github.com/functionalland.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg src=\"./.meta/fl-logo.svg\" alt=\"Functional\" width=\"450\" /\u003e\n\nCommon Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.\n\n[![deno land](http://img.shields.io/badge/available%20on-deno.land/x-lightgrey.svg?logo=deno\u0026labelColor=black)](https://deno.land/x/functional@v1.3.4)\n[![deno version](https://img.shields.io/badge/deno-^1.6.1-lightgrey?logo=deno)](https://github.com/denoland/deno)\n[![GitHub release](https://img.shields.io/github/v/release/sebastienfilion/functional)](https://github.com/sebastienfilion/functional/releases)\n[![GitHub licence](https://img.shields.io/github/license/sebastienfilion/functional)](https://github.com/sebastienfilion/functional/blob/v1.3.4/LICENSE)\n[![Discord Chat](https://img.shields.io/discord/790708610023555093.svg)](https://discord.gg/)\n\n  * [Either](#either)\n  * [IO](#io)\n  * [Maybe](#maybe)\n  * [Pair](#pair)\n  * [Task](#task)\n  * [Type factory](#type-factory)\n  * [Sum Type factory](#sum-type-factory)\n  * [Utilities](#utilities)\n  * [TypeScript](#typescript)\n\n## Usage\n\nThis example uses the [Ramda library](https://ramdajs.com) - for simplification - but you should be able to use any library that implements\nthe [Fantasy-land specifications](https://github.com/fantasyland/fantasy-land).\n\n```js\nimport { compose, converge, curry, map, prop } from \"https://deno.land/x/ramda@v0.27.2/mod.ts\";\nimport Either from \"https://deno.land/x/functional@v1.3.4/library/Either.js\";\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\n\nconst fetchUser = userID =\u003e Task.wrap(_ =\u003e fetch(`${URL}/users/${userID}`).then(response =\u003e response.json()));\n\nconst sayHello = compose(\n  map(\n    converge(\n      curry((username, email) =\u003e `Hello ${username} (${email})!`),\n      [\n        prop(\"username\"),\n        prop(\"email\")\n      ]\n    )\n  ),\n  fetchUser\n);\n\n// Calling `sayHello` results in an instance of `Task` keeping the function pure.\nassert(Task.is(sayHello(userID)));\n\n// Finally, calling `Task#run` will call `fetch` and return a promise\nsayHello(userID).run()\n  .then(container =\u003e {\n    // The returned value should be an instance of `Either.Right` or `Either.Left`\n    assert(Either.Right.is(container));\n    // Forcing to coerce the container to string will show that the final value is our message.\n    assert(container.toString(), `Either.Right(\"Hello johndoe (johndoe@gmail.com)!\")`);\n  });\n\n// await sayHello(userID).run() === Either.Right(String)\n```\n\n### Using the bundle\n\nAs a convenience, when using Functional in the browser, you can use the **unminified** bundled copy (18KB gzipped).\n\n```js\nimport { compose, converge, lift, map, prop } from \"https://deno.land/x/ramda@v0.27.2/mod.ts\";\nimport { Either, Task } from \"https://deno.land/x/functional@v1.3.4/functional.js\";\n\nconst fetchUser = userID =\u003e Task.wrap(_ =\u003e fetch(`${URL}/users/${userID}`).then(response =\u003e response.json()));\n\nconst sayHello = compose(\n  map(\n    converge(\n      curry((username, email) =\u003e `Hello ${username} (${email})!`),\n      [\n        prop(\"username\"),\n        prop(\"email\")\n      ]\n    )\n  ),\n  fetchUser\n);\n```\n\n---\n\n## Either\n\nThe `Either` is a sum type similar to `Maybe`, but it differs in that a value can be of two possible types\n(Left or Right). Commonly the Left type represents an error.\n\nThe `Either` type implements the following algebras:\n- [x] Alternative\n- [x] Comonad\n- [x] Monad\n\n### Example\n\n```js\nimport Either from \"https://deno.land/x/functional@v1.3.4/library/Either.js\";\n\nconst containerA = Either.Right(42).map(x =\u003e x + 2);\nconst containerB = Either.Left(new Error(\"The value is not 42.\")).map(x =\u003e x + 2);\nconst containerC = containerB.alt(containerA);\n\nassert(Either.Right.is(containerA));\nassert(containerA.extract() === 44);\nassert(Either.Left.is(containerB));\nassert(Either.Right.is(containerC));\n```\n\n---\n\nTraverse is an experimental feature; The Naturility law test is failing.\n\n---\n\n## IO\n\nThe `IO` type represents a call to IO. Any Functional Programming purist would tell you that your functions has\nto be pure... But in the real world, this is not very useful. Wrapping your call to IO with `IO` will enable you\nto postpone the side-effect and keep your program (somewhat) pure.\n\nThe `IO` type implements the following algebras:\n- [x] Monad\n\n### Example\n\n```js\nimport IO from \"https://deno.land/x/functional@v1.3.2/library/IO.js\";\n\nconst container = IO(_ =\u003e readFile(`${Deno.cwd()}/dump/hoge`))\n  .map(promise =\u003e promise.then(text =\u003e text.split(\"\\n\")));\n// File isn't being read yet. Still pure.\n\nassert(IO.is(containerA));\n\nconst promise = container.run();\n// Now, the file is being read.\n\nconst lines = await promise;\n```\n\n---\n\n## Maybe\n\nThe `Maybe` is the most common sum type; it represents the possibility of a value being `null` or `undefined`.\n\nThe `Maybe` type implements the following algebras:\n- [x] Alternative\n- [x] Comonad\n- [x] Monad\n\n### Example\n\n```js\nimport Maybe from \"https://deno.land/x/functional@v1.3.2/library/Maybe.js\";\n\nconst containerA = Maybe.Just(42).map(x =\u003e x + 2);\nconst containerB = Maybe.Nothing.map(x =\u003e x + 2);\n\nassert(Maybe.Just.is(containerA));\nassert(containerA.extract() === 44);\nassert(Maybe.Nothing.is(containerB));\n```\n\n---\n\nTraverse is an experimental feature; The Naturility law test is failing.\n\n---\n\n## Pair\n\nThe `Pair` type represents two values.\n\nThe `Pair` type implements the following algebras:\n- [x] Bifunctor\n- [x] Functor\n\n### Example\n\n```js\nimport Pair from \"https://deno.land/x/functional@v1.3.2/library/Pair.js\";\n\nconst pair = Pair(42, 42)\n  .bimap(\n    x =\u003e x * 2,\n    x =\u003e x + 2\n  );\n\nassert(Pair.is(pair));\nassert(pair.first === 84);\nassert(pair.second === 44);\n```\n\n---\n\n## Task\n\nThe `Task` type is similar in concept to `IO`; it helps keep your function pure when you are working with `IO`.\nThe biggest difference with `IO` is that this type considers Promise as first-class citizen. Also, it always resolves\nto an instance of `Either`; `Either.Right` for a success, `Either.Left` for a failure.\n\nThe `IO` type implements the following algebras:\n- [x] Monad\n\n### Example\n\n```js\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\n\nconst containerA = Task(_ =\u003e readFile(`${Deno.cwd()}/dump/hoge`))\n  .map(text =\u003e text.split(\"\\n\"));\n// File isn't being read yet. Still pure.\n\nassert(Task.is(containerA));\n\nconst containerB = await container.run();\n// Now, the file is being read.\n\nassert(Either.Right.is(containerB));\n// The call was successful!\n\nconst lines = containerB.extract();\n```\n\nThe `Task` factory comes with a special utility method called `wrap`. The result of any function called with `wrap`\nwill be memoized allowing for safe \"logic-forks\".\n\nTake the following example; `containerD` contains the raw text, `containerE` contains the text into lines and\n`containerF` contains the lines in inverted order. Because `run` was called thrice, the file was read thrice. 😐\n\n```js\nlet count = 0;\nconst containerA = Task(_ =\u003e ++count \u0026\u0026 readFile(`${Deno.cwd()}/dump/hoge`));\nconst containerB = containerA.map(text =\u003e text.split(\"\\n\"));\nconst containerC = containerB.map(lines =\u003e text.reverse());\n\nassert(Task.is(containerA));\nassert(Task.is(containerB));\nassert(Task.is(containerC));\n\nconst containerD = await containerA.run();\nconst containerE = await containerB.run();\nconst containerF = await containerC.run();\n\nassert(count === 3);\n```\n\nDefinitely not what we want... Simply wrap the function and bim bam boom - memoization magic! (The file will only be\nread once) 🤩\n\nPlease check-out [Functional IO](https://github.com/sebastienfilion/functional-deno-io) for more practical examples.\n\n---\n\n## Type factory\n\nThe Type factory can be used to build complex data structure.\n\n```js\nimport { factorizeType } from \"https://deno.land/x/functional@v1.3.2/library/factories.js\";\n\nconst Coordinates = factorizeType(\"Coordinates\", [ \"x\", \"y\" ]);\nconst vector = Coordinates(150, 200);\n// vector.x === 150\n// vector.y === 200\n```\n\n### Type`.from`\n`Type ~\u003e Object → t`\n\nCreate an instance of Type using an object representation.\n\n```js\nconst vector = Coordinates.from({ x: 150, y: 200 });\n// vector.x === 150\n// vector.y === 200\n```\n\n### Type`.is`\n`Type ~\u003e Type t → Boolean`\n\nAssert that an instance is of the same Type.\n\n```js\nCoordinates.is(vector);\n// true\n```\n\n### Type`.toString`\n`Type ~\u003e () → String`\n\nSerialize the Type Representation into a string.\n\n```js\nCoordinates.toString();\n// \"Coordinates\"\n```\n\n### Type(a)`.toString`\n`Type t =\u003e t ~\u003e () → String`\n\nSerialize the instance into a string.\n\n```js\nvector.toString();\n// \"Coordinates(150, 200)\"\n```\n\n## Sum Type factory\n\n```js\nimport { factorizeSumType } from \"https://deno.land/x/functional@v1.3.2/library/factories.js\";\n\nconst Shape = factorizeSumType(\n  \"Shape\",\n  {\n    // Square :: (Coord, Coord) → Shape\n    Square: [ \"topLeft\", \"bottomRight\" ],\n    // Circle :: (Coord, Number) → Shape\n    Circle: [ \"center\", \"radius\" ]\n  }\n);\n```\n\n### SumType`.from`\n`SumType ~\u003e Object → t`\n\nCreate an instance of Type using an object representation.\n\n```js\nconst oval = Shape.Circle.from(\n  {\n    center: Coordinates.from({ x: 150, y: 200 }),\n    radius: 200\n  }\n);\n// oval.center === Coordinates(150, 200)\n// oval.radius === 200\n```\n\n### SumType`.is`\n`SumType ~\u003e SumType t → Boolean`\n\nAssert that an instance is of the same Sum Type.\n\n```js\nShape.Circle.is(oval);\n// true\n```\n\n### SumType`#fold`\n\n```js\nShape.prototype.translate = function (x, y, z) {\n  return this.fold({\n    Square: (topleft, bottomright) =\u003e\n      Shape.Square(\n        topLeft.translate(x, y, z),\n        bottomRight.translate(x, y, z)\n      ),\n\n    Circle: (centre, radius) =\u003e\n      Shape.Circle(\n        centre.translate(x, y, z),\n        radius\n      )\n  })\n};\n```\n\n### SumType(a)`.toString`\n` SumType t =\u003e t ~\u003e () → String`\n\nSerialize the instance into a string.\n\n```js\noval.toString();\n// \"Shape.Circle(Coordinates(150, 200), 200)\"\n```\n\n@function\n@name factorizeType\n@module functional/SumType\n\n@description Factorize a Type Representation.\n@param {String} typeName\n@param {String[]} propertyNameList\n@return {Function}\n\n@example\nconst Coordinates = factorizeType(\"Coordinates\", [ \"x\", \"y\" ]);\nconst vector = Coordinates(150, 200);\n// vector.x === 150\n// vector.y === 200\n\n---\n\n## Utilities\n\n### `assertIsArray`\n`* → Boolean`\n\n### `assertIsBoolean`\n`* → Boolean`\n\n### `assertIsFunction`\n`* → Boolean`\n\n### `assertIsInstance`\n`* → Boolean`\n\n### `assertIsNull`\n`* → Boolean`\n\n### `assertIsNumber`\n`* → Boolean`\n\n### `assertIsObject`\n`* → Boolean`\n\n### `assertIsRegex`\n`* → Boolean`\n\n### `assertIsString`\n`* → Boolean`\n\n### `assertIsUndefined`\n`* → Boolean`\n\n### `decodeRaw`\n`Uint8Array → String`\n\n### `encodeText`\n`String → Uint8Array`\n\n### `alt`\n`Alt a → Alt b → Alt a|b`\n\nThis function takes a container of any type and, an Alternative functor. Then it returns either the container or the\nalternative functor.\nThe function is in support of the [Alt algebra](https://github.com/fantasyland/fantasy-land#alt).\n\n```js\nimport Either from \"https://deno.land/x/functional@v1.3.4/library/Either.js\";\nimport { alt } from \"https://deno.land/x/functional@v1.3.4/library/utilities.js\";\n\nconst container = alt(Either.Right(42), Either.Left(\"Not the meaning of life\"));\n\nassertEquals(container.extract(), 42);\n```\n\n### `chainLift`\n`(a → b → c) → Chainable a → Functor b → Chainable c`\n\nThis function is similar to [`lift`](https://ramdajs.com/docs/#lift) but is chainable.\n\n```js\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\nimport { chainLift } from \"https://deno.land/x/functional@v1.3.4/library/utilities.js\";\n\nconst hogeFuga = useWith(\n  chainLift(curry((x, y) =\u003e Task.of(x * y))),\n  [\n    x =\u003e Task.of(x),\n    x =\u003e Task.of(x)\n  ]\n);\n\nconst container = await hogeFuga(42, 24).run();\n\nconst value = safeExtract(\"Failed.\", container);\n\nassertEquals(value, 1008);\n```\n\n### `chainRec`\n`ChainRec r =\u003e ((a → c, b → c, a) → r c) → a → r b`\n\nThis function is a combinator for the [`chainRec` algebra](https://github.com/fantasyland/fantasy-land#chainrec).\nIt takes a ternary function, an initial value and, a chainable recursive functor.\n\n```js\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\nimport { chainRec } from \"https://deno.land/x/functional@v1.3.4/library/utilities.js\";\n\nconst multiplyAll = curry((x, n) =\u003e chainRec(\n  (Loop, Done, cursor) =\u003e\n    cursor === n ? Done(Pair(cursor, null)) : Loop(Pair(cursor + 1, Task.of([ x * (cursor + 1) ]))),\n  0\n));\n\nconst container = await multiplyAll(42, 10)(Task.of([ 0 ])).run();\n\nconst value = safeExtract(\"Failed.\", container);\n\nassertEquals(value, [ 0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420 ]);\n```\n\n### `evert`\n`Applicative a =\u003e a → a[] → a`\n\nThis function takes a type constructor and, a list of Applicative functor and evert it; effectively making an Applicative\nfunctor of a list of value.\n\n```js\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\nimport { evert } from \"https://deno.land/x/functional@v1.3.4/library/utilities.js\";\n\nconst container = await evert(Task, [ Task.of(42), Task.of(32), Task.of(24) ]).run();\n\nconst list = safeExtract(\"Failed.\", container);\n\nassertEquals(list, [ 42, 32, 24 ]);\n```\n\n### `log`\n`String → a → a`\n\nThis function is a composable `console.debug`. It takes a message, a value and, return the value.\n\n### `runSequentially`\n`Chain c =\u003e (...c) → c`\n\nThis function takes n Chainable functor and chain them automatically.\n\n```js\nimport Task from \"https://deno.land/x/functional@v1.3.4/library/Task.js\";\nimport { runSequentially } from \"https://deno.land/x/functional@v1.3.4/library/utilities.js\";\n\nconst fuga = converge(\n  runSequentially,\n  [\n    x =\u003e Task.of(x * 2),\n    x =\u003e Task.of(x + 2)\n  ]\n);\n\nconst container = await fuga(42).run();\n\nconst value = safeExtract(\"Failed.\", container);\n\nassertEquals(value, 44);\n```\n\n### `safeExtract`\n`String → Either a → a`\n\nThis function takes a message and an Either container; if the container is `Either.Right`, the value will be\nreturned. But if the container is `Either.Left`, it will throw an error with the message passed.\n\n### `stream`\n`((a, b) → a) → a → AsyncIterable b → a`\n\n---\n\n## TypeScript\n\nYou can import any types or the factories through `mod.ts`.\n\n```ts\nimport {\n  Either,\n  IO,\n  Maybe,\n  Pair,\n  Task,\n  factorizeType,\n  factorySumType\n} from \"https://deno.land/x/functional@v1.3.4/mod.ts\";\n```\n\nOr, you can import individual sub-module with the appropriate TypeScript hint in Deno.\n\n```ts\n// @deno-types=\"https://deno.land/x/functional@v1.3.4/library/Either.d.ts\"\nimport Either from \"https://deno.land/x/functional@v1.3.4/library/Either.js\";\n```\n \n---\n\n## Contributing\n\nWe appreciate your help! Please, [read the guidelines](./CONTRIBUTING.md).\n\n## License\n\nCopyright © 2020 - Sebastien Filion\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the\nSoftware.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nWARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffunctionalland%2Ffunctional","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffunctionalland%2Ffunctional","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffunctionalland%2Ffunctional/lists"}