ramda:根据对象的当前状态设置对象

时间:2018-07-11 19:16:09

标签: javascript functional-programming ramda.js

我想要一个可以设置位置对象的管道。假设定位对象看起来如下所示:

{
  pathname: '/users',
  search: 'sort=desc&sortBy=name',
  hash: '',
  state: {},
}

在管道的第一步中,我想将其state.redirect设置为当前对象,但不包括state。例如,

{
  pathname: '/users',
  search: 'sort=desc&sortBy=name',
  hash: '',
  state: {
    redirect: {
      pathname: '/users',
      search: 'sort=desc&sortBy=name',
      hash: '',
    }
  }
}

我从以下内容开始,但是它并没有真正起作用。

set(lensProp('state'), /* ??? */)

在ramda中执行此操作的合适方法是什么?

2 个答案:

答案 0 :(得分:1)

这应该做到:

const loc = {
  pathname: '/users',
  search: 'sort=desc&sortBy=name',
  hash: '',
  state: {},
}

console.log(R.dissoc('state', loc))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>

Ramda的 What Function Should I Use? 可能有助于查找此类功能。

答案 1 :(得分:0)

下面的方法呢?

const input = {
  pathname: '/users',
  search: 'sort=desc&sortBy=name',
  hash: '',
  state: {},
}

const { lensProp, set, over, dissoc, pipe } = R

// The W combinator to apply twice the same input to a binary function
// W :: (a -> a -> b) -> a -> c
const W = f => x => f (x) (x)

// stateLens :: a -> b
const stateLens = lensProp ('state')

// Note how W will apply the input twice: it'll set the input
// to 'state' property!
// setSelfState :: (Object -> Object -> Object) -> Object -> Object
const setSelfState = W (set (stateLens))

// dissocInnerState :: Object -> Object
const dissocInnerState = over (stateLens) (dissoc ('state'))

// setSelftState :: Object -> Object
const setSelfState_ = pipe (
  setSelfState,
  dissocInnerState
)

const output = setSelfState_ (input)

console.log (output)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>