您可以直接用Ramda使用免费的点对点解决方案。首先,我们定义一个withDefaults
函数,它将在未定义这些方法的对象中设置currentRoom
和messages
方法。
var withDefaults = R.pipe(
// if don't have `currentRom` add a
// `currentRom` function that returns an empty object
R.unless(
R.hasIn('currentRoom'),
R.assoc('currentRoom',
R.always({}))),
// if don't have `messages` add a
// `messages` function that returns an empty array
R.unless(
R.hasIn('messages'),
R.assoc('messages',
R.always([]))))
该功能根据需要过滤对象设置方法。用法示例。
var user = withDefaults(getById(id))
接下来,定义一个getter函数来获取客房和消息从对象。 invoker
是这个snipet的核心部分,它返回一个调用方法的函数。见http://ramdajs.com/docs/#invoker
var getCurrentRoom = R.invoker(0, 'currentRoom')
var getMessages = R.invoker(0, 'messages')
上面的代码可以用作如下。
var userWithRoom = withDefaults({
currentRoom : function() {
return {
number : '123'
}
}
})
var userWithMessages = withDefaults({
messages : function() {
return [
'get lunch'
]
}
})
var userWithAll = withDefaults({
currentRoom : function() {
return {
number : '123'
}
},
messages : function() {
return [
'get lunch'
]
}
})
var userWithNone = withDefaults({})
总之
var withDefaults = R.pipe(
R.unless(
R.hasIn('currentRoom'),
R.assoc('currentRoom',
R.always({}))),
R.unless(
R.hasIn('messages'),
R.assoc('messages',
R.always([]))))
var getCurrentRoom = R.invoker(0, 'currentRoom')
var getMessages = R.invoker(0, 'messages')
// examples
var userWithRoom = withDefaults({
currentRoom : function() {
return {
number : '123'
}
}
})
var userWithMessages = withDefaults({
messages : function() {
return [
'get lunch'
]
}
})
var userWithAll = withDefaults({
currentRoom : function() {
return {
number : '123'
}
},
messages : function() {
return [
'get lunch'
]
}
})
现在让我们用console.log
,看看我们的解决方案可以按预期
console.log(getCurrentRoom(userWithRoom))
console.log(getCurrentRoom(userWithMessages))
console.log(getCurrentRoom(userWithAll))
console.log(getCurrentRoom(userWithNone))
console.log('---')
console.log(getMessages(userWithRoom))
console.log(getMessages(userWithMessages))
console.log(getMessages(userWithAll))
console.log(getMessages(userWithNone))
输出应该是上面的代码测试:
{ number: '123' }
{}
{ number: '123' }
{}
---
[]
[ 'get lunch' ]
[ 'get lunch' ]
[]
顺便说一句,'room'的默认值应该是是'{}'而不是'[]' – Bergi
好点。固定! – gosseti