diff --git a/index.js b/index.js index 3ff0c28c..01b8b884 100644 --- a/index.js +++ b/index.js @@ -1151,6 +1151,8 @@ //. Takes a default value and a Maybe, and returns the Maybe's value //. if the Maybe is a Just; the default value otherwise. //. + //. See also [`maybeToNullable`](#maybeToNullable). + //. //. ```javascript //. > S.fromMaybe(0, S.Just(42)) //. 42 @@ -1164,6 +1166,26 @@ [a, $Maybe(a), a], function(x, maybe) { return maybe.isJust ? maybe.value : x; }); + //# maybeToNullable :: Maybe a -> Nullable a + //. + //. Returns the given Maybe's value if the Maybe is a Just; `null` otherwise. + //. [Nullable][] is defined in sanctuary-def. + //. + //. See also [`fromMaybe`](#fromMaybe). + //. + //. ```javascript + //. > S.maybeToNullable(S.Just(42)) + //. 42 + //. + //. > S.maybeToNullable(S.Nothing()) + //. null + //. ``` + S.maybeToNullable = + def('maybeToNullable', + {}, + [$Maybe(a), $.Nullable(a)], + function(maybe) { return maybe.isJust ? maybe.value : null; }); + //# toMaybe :: a? -> Maybe a //. //. Takes a value and returns Nothing if the value is null or undefined; @@ -3054,6 +3076,7 @@ //. [Functor]: https://github.com/fantasyland/fantasy-land#functor //. [Monad]: https://github.com/fantasyland/fantasy-land#monad //. [Monoid]: https://github.com/fantasyland/fantasy-land#monoid +//. [Nullable]: https://github.com/plaid/sanctuary-def#nullable //. [R.equals]: http://ramdajs.com/docs/#equals //. [R.map]: http://ramdajs.com/docs/#map //. [R.type]: http://ramdajs.com/docs/#type diff --git a/test/maybeToNullable.js b/test/maybeToNullable.js new file mode 100644 index 00000000..762d884e --- /dev/null +++ b/test/maybeToNullable.js @@ -0,0 +1,39 @@ +'use strict'; + +var throws = require('assert').throws; + +var eq = require('./utils').eq; +var errorEq = require('./utils').errorEq; +var S = require('..'); + + +describe('maybeToNullable', function() { + + it('is a unary function', function() { + eq(typeof S.maybeToNullable, 'function'); + eq(S.maybeToNullable.length, 1); + }); + + it('type checks its arguments', function() { + throws(function() { S.maybeToNullable(/XXX/); }, + errorEq(TypeError, + 'Invalid value\n' + + '\n' + + 'maybeToNullable :: Maybe a -> Nullable a\n' + + ' ^^^^^^^\n' + + ' 1\n' + + '\n' + + '1) /XXX/ :: RegExp\n' + + '\n' + + 'The value at position 1 is not a member of ‘Maybe a’.\n')); + }); + + it('can be applied to a Nothing', function() { + eq(S.maybeToNullable(S.Nothing()), null); + }); + + it('can be applied to a Just', function() { + eq(S.maybeToNullable(S.Just(42)), 42); + }); + +});