UNPKG

2.1 kBJavaScriptView Raw
1"use strict";
2
3var assert = require("assert");
4
5/**
6 ### either
7*/
8
9function Left(value) {
10 this.value = value;
11}
12
13function Right(value) {
14 this.value = value;
15}
16
17/**
18 - `either.left(value: a): either a b`
19*/
20function left(value) {
21 return new Left(value);
22}
23
24/**
25 - `either.right(value: b): either a b`
26*/
27function right(value) {
28 return new Right(value);
29}
30
31/**
32 - `either.either(l: a -> x, r: b -> x): x`
33*/
34Left.prototype.either = function lefteither(l) {
35 return l(this.value);
36};
37
38Right.prototype.either = function righteither(l, r) {
39 return r(this.value);
40};
41
42/**
43 - `either.isEqual(other: either a b): bool`
44
45 TODO: add `eq` optional parameter
46*/
47Left.prototype.isEqual = function leftIsEqual(other) {
48 assert(other instanceof Left || other instanceof Right, "isEqual: `other` parameter should be either");
49 return other instanceof Left && this.value === other.value;
50};
51
52Right.prototype.isEqual = function rightIsEqual(other) {
53 assert(other instanceof Left || other instanceof Right, "isEqual: `other` parameter should be either");
54 return other instanceof Right && this.value === other.value;
55};
56
57/**
58 - `either.bimap(f: a -> c, g: b -> d): either c d`
59
60 ```js
61 either.bimap(compose(f, g), compose(h, i)) ≡ either.bimap(g, i).bimap(f, h);
62 ```
63
64*/
65Left.prototype.bimap = function leftBimap(f) {
66 return new Left(f(this.value));
67};
68
69Right.prototype.bimap = function rightBimap(f, g) {
70 return new Right(g(this.value));
71};
72
73/**
74 - `either.first(f: a -> c): either c b`
75
76 ```js
77 either.first(f) ≡ either.bimap(f, utils.identity)
78 ```
79*/
80Left.prototype.first = function leftFirst(f) {
81 return new Left(f(this.value));
82};
83
84Right.prototype.first = function rightFirst() {
85 return this;
86};
87
88/**
89 - `either.second(g: b -> d): either a d`
90
91 ```js
92 either.second(g) === either.bimap(utils.identity, g)
93 ```
94*/
95Left.prototype.second = function leftSecond() {
96 return this;
97};
98
99Right.prototype.second = function rightSecond(g) {
100 return new Right(g(this.value));
101};
102
103module.exports = {
104 left: left,
105 right: right,
106};