Monoid

Simple monoid factory in JavaScript. Compatible with the Fantasy Land JS Spec.
Easily define list reductions by providing an identity value and a binary function. Get a free way to reduce a list of monoids with concatAll
.
Examples
Make a monoid and concat
two monoid values.
var M = require('monoid');
var Any = M.Monoid({
identity : false,
binary : function (v1, v2) {
return v1 || v2;
}
});
Any(true).append(Any(false));
M.append(Any(true), Any(false));
M.concatAll([Any(false), Any(false), Any(true)]);
M.concatAll([Any(false), Any(false), Any(false)]);
Create a function to reduce a list of values using applyWith
.
var any = M.applyWith(Any);
any([false, false, true]);
any([false, false, false]);
var Product = M.Monoid({
identity : 1,
binary : function (v1, v2) {
return v1 * v2;
}
});
M.applyWith(Product, [3, 5, 10]);
Note: M.applyWith(<Monoid>, list)
is equivelent to M.extract(M.concatAll(list.map(<Monoid>)))
.
Use shorthand syntax for defining binaries. Currently available for +
, *
, ||
and &&
.
var Sum = M.Monoid({
identity : 0,
binary : '+'
});
var sum = M.applyWith(Sum);
sum([10, 32, 11])
TODO
- More examples/docs
- Add more built in binaries
- Consider additional shorthand
var Any = M.Monoid(false, '||')
.