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
  • Loading branch information
rjmk committed Sep 2, 2016
1 parent 896ee17 commit 5dcf0d9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
27 changes: 26 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1265,7 +1265,7 @@

//# toMaybe :: a? -> Maybe a
//.
//. Takes a value and returns Nothing if the value is null or undefined;
//. Takes a value and returns Nothing if the value is `null` or `undefined`;
//. Just the value otherwise.
//.
//. ```javascript
Expand Down Expand Up @@ -1883,6 +1883,31 @@
[b, $Either(a, b), b],
function(x, either) { return either.isRight ? either.value : x; });

//# 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', 'ftp://example.com/'.match(/^https?:/)))
//. Left('Invalid protocol')
//.
//. > R.map(R.head, S.toEither('Invalid protocol', 'https://example.com/'.match(/^https?:/)))
//. Right('https:')
//. ```
S.toEither =
def('toEither',
{},
[a, b, $Either(a, b)],
function(x, y) { return y == null ? Left(x) : Right(y); });

//# either :: (a -> c) -> (b -> c) -> Either a b -> c
//.
//. Takes two functions and an Either, and returns the result of
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 5dcf0d9

Please sign in to comment.