当值是Just

时间:2018-12-05 07:07:32

标签: ramda.js sanctuary

我想在值为Just时设置对象的属性,而在值为Nothing时不设置属性。但是,如果值为Nothing,则返回的对象将变为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)

1 个答案:

答案 0 :(得分:1)

您的Person类型似乎是这样的:

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

如果可能的话,我建议避免使用nullundefined和可选的记录字段,因为它们都是bug的来源。我建议这样:

//    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);

在这种情况下,如果由于某种原因必须有一个可选的address字段,则可以使用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);

结果将为{name: 'Franz'}或类似{name: 'Franz', address: 'Frankfurter Allee 42'}的值。但是,正如我所提到的,{name: 'Franz', address: S.Nothing}{name: 'Franz', address: S.Just ('Frankfurter Allee 42')}是这些“人”的首选表示形式。