mini-fn
The minimal functional programming library.
mini-fn provides simple, tiny library having functional features and its type
declarations.
Examples
You can pipe your functions with Cat<T>
's feed<U>(f: (t: T) => U): Cat<U>
method like this:
import { Cat } from "@mikuroxina/mini-fn";
const result = Cat.cat(-3)
.feed((x) => x ** 2)
.feed((x) => x.toString());
console.log(result.value);
And there are some useful types such as Option<T>
, Result<E, T>
, and so on.
import { Option } from "@mikuroxina/mini-fn";
const sqrtThenToString = (num: number): Option.Option<string> => {
if (num < 0) {
return Option.none();
}
return Option.some(Math.sqrt(num).toString());
};
const applied = Option.andThen(sqrtThenToString);
applied(Option.some(4));
applied(Option.some(-1));
applied(Option.none());
Some of them also provides its monad implementation, so you can combine and
transform them like this:
import { Cat, Option } from "@mikuroxina/mini-fn";
const half = (x: number): Option.Option<number> => {
if (x % 2 != 0) {
return Option.none();
}
return Option.some(x / 2);
};
const liftedHalf = Option.monad.flatMap(half);
Cat.cat(20)
.feed(Option.monad.pure)
.feed(liftedHalf)
.feed(Cat.log)
.feed(liftedHalf)
.feed(Cat.log)
.feed(liftedHalf)
.feed(Cat.log);
Also CatT
allows you to compute with a Monad
environment as:
import { Cat, List } from "@mikuroxina/mini-fn";
const patterns = Cat.doT(List.monad)
.addM("x", List.range(0, 6))
.addMWith("y", ({ x }) => List.range(0, 6 - x))
.addMWith("z", ({ x, y }) => 5 - (x + y))
.finish(({ x, y, z }) => [x, y, z] as const);
console.dir(List.toArray(patterns));