【问题标题】:Ramda.js: How to pass same argument when we composeRamda.js:当我们编写时如何传递相同的参数
【发布时间】:2021-12-30 05:05:30
【问题描述】:

我必须遵循以下代码:

R.map(
  object => ({
    ...object,
    sth: R.compose(
     R.filter(R.propEq('key', val)),
     R.prop('sth')
    )(object)
  }),
  array
)

有没有办法把它写得更干净,而不需要将文字函数传递给映射。我们希望 R.asoc 将 compose 的结果传递给对象。但是我们需要将与第三个 arg 相同的 arg 传递给 assoc,因为我们得到了正确的值,但是我们需要使用与 source 相同的对象来从 assoc 中复制:

R.map(
  R.compose(
    R.assoc('sth'),
    R.filter(R.propEq('key', val)),
    R.prop('sth')
  ),
  array
)

【问题讨论】:

  • 你能添加一些示例数据吗? val 来自哪里?

标签: javascript functional-programming ramda.js


【解决方案1】:

如果没有一些示例数据,我主要是在这里进行猜测。但我认为这可能会做你想做的事:

const matchSth = (val) => map (
  over (lensProp ('sth')) (filter (propEq ('key') (val)))
)

const arr = [
  {foo: 1, sth: [{key: 2, bar: 'a'}, {key: 1, bar: 'b'}, {key: 2, bar: 'c'}, ], baz: 3},
  {foo: 2, sth: [{key: 1, bar: 'c'}, {key: 1, bar: 'd'}, {key: 2, bar: 'e'}, ], baz: 5}
]

console .log (matchSth (2) (arr))
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script>const {map, over, lensProp, filter, propEq} = R                 </script>

镜头是非常有用的抽象,这里lensProp ('sth') 将我们的注意力集中在其目标的sth 属性上。 over 克隆一个对象,除了它将提供的函数应用于该焦点处的值。这里我们传递一个函数来过滤那些key 属性与提供的值匹配的人。

虽然我们当然可以找到一种方法让这一点变得毫无意义,但我发现它本身是可读和可理解的,并且可能不会费心去追求它。

【讨论】:

    【解决方案2】:

    您可以使用R.evolve 转换对象的某些属性而不影响其他属性:

    const { map, evolve, filter, propEq } = R
    
    const matchSth = val => map(evolve({
      sth: filter(propEq('key', val))
    }))
    
    const arr = [{"foo":1,"sth":[{"key":2,"bar":"a"},{"key":1,"bar":"b"},{"key":2,"bar":"c"}],"baz":3},{"foo":2,"sth":[{"key":1,"bar":"c"},{"key":1,"bar":"d"},{"key":2,"bar":"e"}],"baz":5}]
    
    console.log(matchSth(2)(arr))
    .as-console-wrapper {max-height: 100% !important; top: 0}
    &lt;script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 是的,这可能比我的over (lensProp (...), ...) 解决方案更简单。
    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    相关资源
    最近更新 更多