Skip to content

Commit

Permalink
Merge pull request #190 from plaid/dc-maybe-to-nullable
Browse files Browse the repository at this point in the history
maybe: add S.maybeToNullable
  • Loading branch information
davidchambers committed Apr 23, 2016
2 parents e3c2db2 + 69715bb commit 91cf8d6
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
23 changes: 23 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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
Expand Down
39 changes: 39 additions & 0 deletions test/maybeToNullable.js
Original file line number Diff line number Diff line change
@@ -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);
});

});

0 comments on commit 91cf8d6

Please sign in to comment.