diff --git a/index.js b/index.js index 37c18808..ca20712b 100644 --- a/index.js +++ b/index.js @@ -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 diff --git a/test/fromEither.js b/test/fromEither.js new file mode 100644 index 00000000..76932473 --- /dev/null +++ b/test/fromEither.js @@ -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); + }); + +});