Skip to content

Commit

Permalink
Add S.fromEither to pull out values from either
Browse files Browse the repository at this point in the history
S.fromEither :: b -> Either a b -> b

Closes: #130
  • Loading branch information
wennergr committed Jun 7, 2016
1 parent 9051b88 commit be1f26e
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1876,6 +1876,24 @@
[$Either(a, b), $.Boolean],
prop('isRight'));

//# fromEither :: b -> Either a b -> b
//.
//. Takes a default value and an Either, and returns the Right value
//. if the Either is a Right; the default value otherwise.
//.
//. ```javascript
//. > S.fromEither(0, S.Right(42))
//. 42
//.
//. > S.fromEither(0, S.Left(42))
//. 0
//. ```
S.fromEither =
def('fromEither',
{},
[b, $Either(a, b), b],
function(x, either) { return either.isRight ? either.value : x; });

//# either :: (a -> c) -> (b -> c) -> Either a b -> c
//.
//. Takes two functions and an Either, and returns the result of
Expand Down
41 changes: 41 additions & 0 deletions test/fromEither.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use strict';

var throws = require('assert').throws;

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

describe('fromEither', function() {

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

it('type checks its arguments', function() {
throws(function() { S.fromEither(0, [1, 2, 3]); },
'Invalid value\n' +
'\n' +
'fromEither :: b -> Either a b -> b\n' +
' ^^^^^^^^^^n' +
' 1\n' +
'\n' +
'1) [1, 2, 3] :: Array Number, Array FiniteNumber, Array NonZeroFiniteNumber, Array Integer, Array ValidNumber\n' +
'\n' +
'The value at position 1 is not a member of ‘Either a b’.\n');
});

it('can be applied to a Right', function() {
eq(S.fromEither(0, S.Right(42)), 42);
});

it('can be applied to a Left', function() {
eq(S.fromEither(0, S.Left(42)), 0);
});

it('is curried', function() {
eq(S.fromEither(0).length, 1);
eq(S.fromEither(0)(S.Right(42)), 42);
});

});

0 comments on commit be1f26e

Please sign in to comment.