Common Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.
Common Functional Programming Algebraic data types for JavaScript that is compatible with most modern browsers and Deno.
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/[email protected]/mod.ts";
import Either from "https://deno.land/x/[email protected]/library/Either.js";
import Task from "https://deno.land/x/[email protected]/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 ([email protected])!")`);
});
// await sayHello(userID).run() === Either.Right(String)
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/[email protected]/mod.ts";
import { Either, Task } from "https://deno.land/x/[email protected]/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
);
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:
import Either from "https://deno.land/x/[email protected]/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.
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:
import IO from "https://deno.land/x/[email protected]/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;
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:
import Maybe from "https://deno.land/x/[email protected]/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.
The Pair
type represents two values.
The Pair
type implements the following algebras:
import Pair from "https://deno.land/x/[email protected]/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);
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:
import Task from "https://deno.land/x/[email protected]/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.
The Type factory can be used to build complex data structure.
import { factorizeType } from "https://deno.land/x/[email protected]/library/factories.js";
const Coordinates = factorizeType("Coordinates", [ "x", "y" ]);
const vector = Coordinates(150, 200);
// vector.x === 150
// vector.y === 200
.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
.is
Type ~> Type t β Boolean
Assert that an instance is of the same Type.
Coordinates.is(vector);
// true
.toString
Type ~> () β String
Serialize the Type Representation into a string.
Coordinates.toString();
// "Coordinates"
.toString
Type t => t ~> () β String
Serialize the instance into a string.
vector.toString();
// "Coordinates(150, 200)"
import { factorizeSumType } from "https://deno.land/x/[email protected]/library/factories.js";
const Shape = factorizeSumType(
"Shape",
{
// Square :: (Coord, Coord) β Shape
Square: [ "topLeft", "bottomRight" ],
// Circle :: (Coord, Number) β Shape
Circle: [ "center", "radius" ]
}
);
.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
.is
SumType ~> SumType t β Boolean
Assert that an instance is of the same Sum Type.
Shape.Circle.is(oval);
// true
#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
)
})
};
.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 {String} typeName
@param {String[]} propertyNameList
@return {Function}
@example
const Coordinates = factorizeType(βCoordinatesβ, [ βxβ, βyβ ]);
const vector = Coordinates(150, 200);
// vector.x === 150
// vector.y === 200
assertIsArray
* β Boolean
assertIsBoolean
* β Boolean
assertIsFunction
* β Boolean
assertIsInstance
* β Boolean
assertIsNull
* β Boolean
assertIsNumber
* β Boolean
assertIsObject
* β Boolean
assertIsRegex
* β Boolean
assertIsString
* β Boolean
assertIsUndefined
* β Boolean
decodeRaw
Uint8Array β String
encodeText
String β Uint8Array
alt
Alt a β Alt b β Alt a|b
This function takes a container of any type and, an Alternative functor. Then it returns either the container or the
alternative functor.
The function is in support of the Alt algebra.
import Either from "https://deno.land/x/[email protected]/library/Either.js";
import { alt } from "https://deno.land/x/[email protected]/library/utilities.js";
const container = alt(Either.Right(42), Either.Left("Not the meaning of life"));
assertEquals(container.extract(), 42);
chainLift
(a β b β c) β Chainable a β Functor b β Chainable c
This function is similar to lift
but is chainable.
import Task from "https://deno.land/x/[email protected]/library/Task.js";
import { chainLift } from "https://deno.land/x/[email protected]/library/utilities.js";
const hogeFuga = useWith(
chainLift(curry((x, y) => Task.of(x * y))),
[
x => Task.of(x),
x => Task.of(x)
]
);
const container = await hogeFuga(42, 24).run();
const value = safeExtract("Failed.", container);
assertEquals(value, 1008);
chainRec
ChainRec r => ((a β c, b β c, a) β r c) β a β r b
This function is a combinator for the chainRec
algebra.
It takes a ternary function, an initial value and, a chainable recursive functor.
import Task from "https://deno.land/x/[email protected]/library/Task.js";
import { chainRec } from "https://deno.land/x/[email protected]/library/utilities.js";
const multiplyAll = curry((x, n) => chainRec(
(Loop, Done, cursor) =>
cursor === n ? Done(Pair(cursor, null)) : Loop(Pair(cursor + 1, Task.of([ x * (cursor + 1) ]))),
0
));
const container = await multiplyAll(42, 10)(Task.of([ 0 ])).run();
const value = safeExtract("Failed.", container);
assertEquals(value, [ 0, 42, 84, 126, 168, 210, 252, 294, 336, 378, 420 ]);
evert
Applicative a => a β a[] β a
This function takes a type constructor and, a list of Applicative functor and evert it; effectively making an Applicative
functor of a list of value.
import Task from "https://deno.land/x/[email protected]/library/Task.js";
import { evert } from "https://deno.land/x/[email protected]/library/utilities.js";
const container = await evert(Task, [ Task.of(42), Task.of(32), Task.of(24) ]).run();
const list = safeExtract("Failed.", container);
assertEquals(list, [ 42, 32, 24 ]);
log
String β a β a
This function is a composable console.debug
. It takes a message, a value and, return the value.
runSequentially
Chain c => (...c) β c
This function takes n Chainable functor and chain them automatically.
import Task from "https://deno.land/x/[email protected]/library/Task.js";
import { runSequentially } from "https://deno.land/x/[email protected]/library/utilities.js";
const fuga = converge(
runSequentially,
[
x => Task.of(x * 2),
x => Task.of(x + 2)
]
);
const container = await fuga(42).run();
const value = safeExtract("Failed.", container);
assertEquals(value, 44);
safeExtract
String β Either a β a
This function takes a message and an Either container; if the container is Either.Right
, the value will be
returned. But if the container is Either.Left
, it will throw an error with the message passed.
stream
((a, b) β a) β a β AsyncIterable b β a
You can import any types or the factories through mod.ts
.
import {
Either,
IO,
Maybe,
Pair,
Task,
factorizeType,
factorySumType
} from "https://deno.land/x/[email protected]/mod.ts";
Or, you can import individual sub-module with the appropriate TypeScript hint in Deno.
// @deno-types="https://deno.land/x/[email protected]/library/Either.d.ts"
import Either from "https://deno.land/x/[email protected]/library/Either.js";
We appreciate your help! Please, read the guidelines.
Copyright Β© 2020 - Sebastien Filion
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the βSoftwareβ), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED βAS ISβ, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.