如何在 Ramda 中的对象属性之间移动值?
How can I move values between properties of an object in Ramda?
我有以下对象:
var player = {
cards: [1,2,3,4,5],
hand: []
}
我想将 cards
属性 的一些项目移动到 hand
。
我虽然考虑过使用镜头来防止对象发生变异,但无法找到一种解决方案,让我只需要组合函数就可以做到。也许不应该那样做。
我能做的最好的是:
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)
}
这是一个版本:
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]}
但我什至不会尝试让这样的东西免分。我不确定我该怎么做,但如果我可以,我很确定它会更难阅读。
您可以在 Ramda REPL.
上看到它的实际效果
我有以下对象:
var player = {
cards: [1,2,3,4,5],
hand: []
}
我想将 cards
属性 的一些项目移动到 hand
。
我虽然考虑过使用镜头来防止对象发生变异,但无法找到一种解决方案,让我只需要组合函数就可以做到。也许不应该那样做。
我能做的最好的是:
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)
}
这是一个版本:
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]}
但我什至不会尝试让这样的东西免分。我不确定我该怎么做,但如果我可以,我很确定它会更难阅读。
您可以在 Ramda REPL.
上看到它的实际效果