あなただけ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))
次に、ゲッター関数を定義して、オブジェクトから部屋とメッセージを取得します。 invoker
はこのスニペットの中心部分であり、メソッドを呼び出す関数を返します。 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(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))
当社のソリューションが動作するかどうかを確認するためにconsole.log
を使用して、出力は次のようになります。
{ number: '123' }
{}
{ number: '123' }
{}
---
[]
[ 'get lunch' ]
[ 'get lunch' ]
[]
ところで、 'room'のデフォルト値は'[] 'ではなく{{}'である – Bergi
良い点。一定! – gosseti