0

I would like to set the property of an object when the value is Just, and not to set the property when the value is Nothing. However, if the value is Nothing, the returned object become Nothing.

let person = {name: 'Franz'}
const address = getAddress(response) // getAddress returns Maybe

// person will be Nothing if address is Nothing 
person = S.map(R.assoc('address', R.__, person))(address)
4

1 回答 1

1

It seems your Person type is something like this:

Person = { name :: String, (address :: Address)? }

If at all possible, I suggest avoiding null, undefined, and optional record fields as these are all sources of bugs. I suggest something like this:

//    person :: Person
const person = {name: 'Franz', address: S.Nothing};

//    address :: Maybe Address
const address = getAddress (response);

//    person$ :: Person
const person$ = R.assoc ('address') (address) (person);

If for some reason you must have an optional address field in this case, you could use S.maybe:

//    person :: Person
const person = {name: 'Franz'}

//    address :: Maybe Address
const address = getAddress (response);

//    person$ :: Person
const person$ = S.maybe (person)
                        (address => R.assoc ('address') (address) (person))
                        (address);

The result will either be {name: 'Franz'} or something like {name: 'Franz', address: 'Frankfurter Allee 42'}. As I mentioned, though, {name: 'Franz', address: S.Nothing} and {name: 'Franz', address: S.Just ('Frankfurter Allee 42')} are preferable representations of these “people”.

于 2018-12-05T12:30:06.500 回答