[英]How can I move values between properties of an object in Ramda?
I have the following object: 我有以下对象:
var player = {
cards: [1,2,3,4,5],
hand: []
}
I want to move some items of the cards
property into hand
. 我想把
cards
属性中的一些物品移到hand
。
I though of using lenses to keep from mutating the object, but could not arrive at a solution that would allow me to do it just composing functions. 我虽然使用镜头来防止物体发生变化,但无法找到一种解决方案,让我仅通过组合功能就可以做到这一点。 Maybe it's not supposed to be done that way.
也许不应该那样做。
The best I could do is as following: 我能做的最好的事情如下:
function drawIntoHand(amount, player) {
const deck = R.lensProp('cards')
const hand = R.lensProp('hand')
let cardsRemoved = R.over(deck, R.take(amount), player)
R.set(hand, R.append(cardsRemoved), player)
return R.set(deck, R.drop(amount), player)
}
Here is one version: 这是一个版本:
const drawIntoHand = (() => {
const deck = lensProp('cards');
const hand = lensProp('hand');
return (amount, player) => {
const draw = take(amount, view(deck, player));
return over(deck, drop(amount), over(hand, concat(draw), player));
};
})();
drawIntoHand(3, player); //=> {"cards": [4, 5], "hand": [1, 2, 3]}
But I wouldn't even attempt to make something like this points-free. 但是,我什至不会尝试做出类似这样的观点。 I'm not sure how I could do it, but if I could, I'm quite certain it would be much harder to read.
我不确定该怎么做,但是如果可以的话,我敢肯定它会更难阅读。
You can see it in action on the Ramda REPL . 您可以在Ramda REPL上看到它的运行情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.