Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add S.fromEither to pull out values from either #229

Merged
merged 1 commit into from
Jun 7, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The expressions and the accompanying descriptions should be switched. ;)


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

});