From 5dcf0d9782f57dafa9a7813ba80d41d34f7387a8 Mon Sep 17 00:00:00 2001 From: rjmk Date: Fri, 2 Sep 2016 01:34:18 +0100 Subject: [PATCH] Adds `toEither :: a -> b? -> Either a b` A function for converting a possibly null-y value to an Either --- index.js | 27 ++++++++++++++++++++++++++- test/toEither.js | 23 +++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 test/toEither.js diff --git a/index.js b/index.js index eb2c50a1..275d724d 100644 --- a/index.js +++ b/index.js @@ -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 @@ -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 diff --git a/test/toEither.js b/test/toEither.js new file mode 100644 index 00000000..407fb48b --- /dev/null +++ b/test/toEither.js @@ -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)); + }); + +});