简体   繁体   中英

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM