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 d269f79
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
18 changes: 18 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2060,6 +2060,24 @@
return either.isLeft ? Nothing() : Just(either.value);
});

//# 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; });

//. ### Alternative

// Alternative :: TypeClass
Expand Down
42 changes: 42 additions & 0 deletions test/fromEither.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'use strict';

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

var eq = require('./utils').eq;
var errorEq = require('./utils').errorEq;
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 Left', function() {
eq(S.fromEither(0, S.Right(42)), 42);
});

it('can be applied to a Right', 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 d269f79

Please sign in to comment.