Skip to content

Commit

Permalink
Adds toEither :: a -> b? -> Either a b
Browse files Browse the repository at this point in the history
A function for converting a possibly null-y value to an Either
Closes #83
  • Loading branch information
rjmk committed Sep 2, 2016
1 parent 896ee17 commit 9ec6fee
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
25 changes: 25 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1943,6 +1943,31 @@
return either.isRight ? [either.value] : [];
}));

//# toEither :: a -> b? -> Either a b
//.
//. Converts an arbitrary value to an Either: a Left if the value is `null`
//. or `undefined`; a Right otherwise. The first argument specifies the
//. value of the Left in the "failure" case.
//.
//. ```javascript
//. > S.toEither("XYZ", null)
//. Left("XYZ")
//.
//. > S.toEither("XYZ", "ABC")
//. Right("ABC")
//.
//. > R.map(R.head, S.toEither("Invalid protocol", "https://example.com/".match(/^https?:\/\//)))
//. Right("https://")
//.
//. > R.map(R.head, S.toEither("Invalid protocol", "ftp://example.com/".match(/^https?:\/\//)))
//. Left("Invalid protocol")
//. ```
S.toEither =
def('toEither',
{},
[a, b, $Either(a, b)],
function(x, y) { return y == null ? Left(x) : Right(y); });

//# encaseEither :: (Error -> l) -> (a -> r) -> a -> Either l r
//.
//. Takes two unary functions, `f` and `g`, the second of which may throw,
Expand Down
23 changes: 23 additions & 0 deletions test/toEither.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
'use strict';

var eq = require('./utils').eq;
var S = require('..');


describe('toEither', function() {

it('is a binary function', function() {
eq(typeof S.toEither, 'function');
eq(S.toEither.length, 2);
});

it('returns Left of the first argument when second argument is `null`-y', function() {
eq(S.toEither('a', null), S.Left('a'));
eq(S.toEither('a', undefined), S.Left('a'));
});

it('returns a Right of the second argument when it is not `null`-y', function() {
eq(S.toEither('a', 42), S.Right(42));
});

});

0 comments on commit 9ec6fee

Please sign in to comment.