SkillAgentSearch skills...

Functional

Common Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.

Install / Use

/learn @functionalland/Functional

README

<img src="./.meta/fl-logo.svg" alt="Functional" width="450" />

Common Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.

deno land deno version GitHub release GitHub licence Discord Chat

Usage

This example uses the Ramda library - for simplification - but you should be able to use any library that implements the Fantasy-land specifications.

import { compose, converge, curry, map, prop } from "https://deno.land/x/ramda@v0.27.2/mod.ts";
import Either from "https://deno.land/x/functional@v1.3.4/library/Either.js";
import Task from "https://deno.land/x/functional@v1.3.4/library/Task.js";

const fetchUser = userID => Task.wrap(_ => fetch(`${URL}/users/${userID}`).then(response => response.json()));

const sayHello = compose(
  map(
    converge(
      curry((username, email) => `Hello ${username} (${email})!`),
      [
        prop("username"),
        prop("email")
      ]
    )
  ),
  fetchUser
);

// Calling `sayHello` results in an instance of `Task` keeping the function pure.
assert(Task.is(sayHello(userID)));

// Finally, calling `Task#run` will call `fetch` and return a promise
sayHello(userID).run()
  .then(container => {
    // The returned value should be an instance of `Either.Right` or `Either.Left`
    assert(Either.Right.is(container));
    // Forcing to coerce the container to string will show that the final value is our message.
    assert(container.toString(), `Either.Right("Hello johndoe (johndoe@gmail.com)!")`);
  });

// await sayHello(userID).run() === Either.Right(String)

Using the bundle

As a convenience, when using Functional in the browser, you can use the unminified bundled copy (18KB gzipped).

import { compose, converge, lift, map, prop } from "https://deno.land/x/ramda@v0.27.2/mod.ts";
import { Either, Task } from "https://deno.land/x/functional@v1.3.4/functional.js";

const fetchUser = userID => Task.wrap(_ => fetch(`${URL}/users/${userID}`).then(response => response.json()));

const sayHello = compose(
  map(
    converge(
      curry((username, email) => `Hello ${username} (${email})!`),
      [
        prop("username"),
        prop("email")
      ]
    )
  ),
  fetchUser
);

Either

The Either is a sum type similar to Maybe, but it differs in that a value can be of two possible types (Left or Right). Commonly the Left type represents an error.

The Either type implements the following algebras:

  • [x] Alternative
  • [x] Comonad
  • [x] Monad

Example

import Either from "https://deno.land/x/functional@v1.3.4/library/Either.js";

const containerA = Either.Right(42).map(x => x + 2);
const containerB = Either.Left(new Error("The value is not 42.")).map(x => x + 2);
const containerC = containerB.alt(containerA);

assert(Either.Right.is(containerA));
assert(containerA.extract() === 44);
assert(Either.Left.is(containerB));
assert(Either.Right.is(containerC));

Traverse is an experimental feature; The Naturility law test is failing.


IO

The IO type represents a call to IO. Any Functional Programming purist would tell you that your functions has to be pure... But in the real world, this is not very useful. Wrapping your call to IO with IO will enable you to postpone the side-effect and keep your program (somewhat) pure.

The IO type implements the following algebras:

  • [x] Monad

Example

import IO from "https://deno.land/x/functional@v1.3.2/library/IO.js";

const container = IO(_ => readFile(`${Deno.cwd()}/dump/hoge`))
  .map(promise => promise.then(text => text.split("\n")));
// File isn't being read yet. Still pure.

assert(IO.is(containerA));

const promise = container.run();
// Now, the file is being read.

const lines = await promise;

Maybe

The Maybe is the most common sum type; it represents the possibility of a value being null or undefined.

The Maybe type implements the following algebras:

  • [x] Alternative
  • [x] Comonad
  • [x] Monad

Example

import Maybe from "https://deno.land/x/functional@v1.3.2/library/Maybe.js";

const containerA = Maybe.Just(42).map(x => x + 2);
const containerB = Maybe.Nothing.map(x => x + 2);

assert(Maybe.Just.is(containerA));
assert(containerA.extract() === 44);
assert(Maybe.Nothing.is(containerB));

Traverse is an experimental feature; The Naturility law test is failing.


Pair

The Pair type represents two values.

The Pair type implements the following algebras:

  • [x] Bifunctor
  • [x] Functor

Example

import Pair from "https://deno.land/x/functional@v1.3.2/library/Pair.js";

const pair = Pair(42, 42)
  .bimap(
    x => x * 2,
    x => x + 2
  );

assert(Pair.is(pair));
assert(pair.first === 84);
assert(pair.second === 44);

Task

The Task type is similar in concept to IO; it helps keep your function pure when you are working with IO. The biggest difference with IO is that this type considers Promise as first-class citizen. Also, it always resolves to an instance of Either; Either.Right for a success, Either.Left for a failure.

The IO type implements the following algebras:

  • [x] Monad

Example

import Task from "https://deno.land/x/functional@v1.3.4/library/Task.js";

const containerA = Task(_ => readFile(`${Deno.cwd()}/dump/hoge`))
  .map(text => text.split("\n"));
// File isn't being read yet. Still pure.

assert(Task.is(containerA));

const containerB = await container.run();
// Now, the file is being read.

assert(Either.Right.is(containerB));
// The call was successful!

const lines = containerB.extract();

The Task factory comes with a special utility method called wrap. The result of any function called with wrap will be memoized allowing for safe "logic-forks".

Take the following example; containerD contains the raw text, containerE contains the text into lines and containerF contains the lines in inverted order. Because run was called thrice, the file was read thrice. 😐

let count = 0;
const containerA = Task(_ => ++count && readFile(`${Deno.cwd()}/dump/hoge`));
const containerB = containerA.map(text => text.split("\n"));
const containerC = containerB.map(lines => text.reverse());

assert(Task.is(containerA));
assert(Task.is(containerB));
assert(Task.is(containerC));

const containerD = await containerA.run();
const containerE = await containerB.run();
const containerF = await containerC.run();

assert(count === 3);

Definitely not what we want... Simply wrap the function and bim bam boom - memoization magic! (The file will only be read once) 🤩

Please check-out Functional IO for more practical examples.


Type factory

The Type factory can be used to build complex data structure.

import { factorizeType } from "https://deno.land/x/functional@v1.3.2/library/factories.js";

const Coordinates = factorizeType("Coordinates", [ "x", "y" ]);
const vector = Coordinates(150, 200);
// vector.x === 150
// vector.y === 200

Type.from

Type ~> Object → t

Create an instance of Type using an object representation.

const vector = Coordinates.from({ x: 150, y: 200 });
// vector.x === 150
// vector.y === 200

Type.is

Type ~> Type t → Boolean

Assert that an instance is of the same Type.

Coordinates.is(vector);
// true

Type.toString

Type ~> () → String

Serialize the Type Representation into a string.

Coordinates.toString();
// "Coordinates"

Type(a).toString

Type t => t ~> () → String

Serialize the instance into a string.

vector.toString();
// "Coordinates(150, 200)"

Sum Type factory

import { factorizeSumType } from "https://deno.land/x/functional@v1.3.2/library/factories.js";

const Shape = factorizeSumType(
  "Shape",
  {
    // Square :: (Coord, Coord) → Shape
    Square: [ "topLeft", "bottomRight" ],
    // Circle :: (Coord, Number) → Shape
    Circle: [ "center", "radius" ]
  }
);

SumType.from

SumType ~> Object → t

Create an instance of Type using an object representation.

const oval = Shape.Circle.from(
  {
    center: Coordinates.from({ x: 150, y: 200 }),
    radius: 200
  }
);
// oval.center === Coordinates(150, 200)
// oval.radius === 200

SumType.is

SumType ~> SumType t → Boolean

Assert that an instance is of the same Sum Type.

Shape.Circle.is(oval);
// true

SumType#fold

Shape.prototype.translate = function (x, y, z) {
  return this.fold({
    Square: (topleft, bottomright) =>
      Shape.Square(
        topLeft.translate(x, y, z),
        bottomRight.translate(x, y, z)
      ),

    Circle: (centre, radius) =>
      Shape.Circle(
        centre.translate(x, y, z),
        radius
      )
  })
};

SumType(a).toString

SumType t => t ~> () → String

Serialize the instance into a string.

oval.toString();
// "Shape.Circle(Coordinates(150, 200), 200)"

@function @name factorizeType @module functional/SumType

@description Factorize a Type Representation. @param

View on GitHub
GitHub Stars112
CategoryDevelopment
Updated2mo ago
Forks2

Languages

JavaScript

Security Score

100/100

Audited on Jan 26, 2026

No findings