简体   繁体   English

Ramda.js:当我们编写时如何传递相同的参数

[英]Ramda.js: How to pass same argument when we compose

I have to following code:我必须遵循代码:

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

Is there a way to write it cleaner, without passing literal function to map.有没有办法把它写得更干净,而不需要将文字 function 传递给 map。 We want to R.assoc the result of compose to object.我们想将 R.asoc 组合到 object 的结果。 But we need to pass the same arg to assoc as 3rd arg, because we get the correct value, but we need to use same object as source to make a copy from in assoc:但是我们需要将与第三个 arg 相同的 arg 传递给 assoc,因为我们得到了正确的值,但是我们需要使用相同的 object 作为源来从 assoc 中复制:

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

Without some sample data, I'm mostly making a guess here.没有一些样本数据,我主要是在这里猜测。 But I think this might do what you want:但我认为这可能会做你想要的:

 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>

Lenses are very useful abstractions, and here lensProp ('sth') focuses our attention on the sth property of its target. Lenses 是非常有用的抽象,这里lensProp ('sth')将我们的注意力集中在其目标的sth属性上。 over clones an object, except that it applies the function supplied to the value at that focus. over克隆 object,除了它将提供的 function 应用于该焦点处的值。 Here we pass a function which filters those whose key properties match the supplied value.在这里,我们传递了一个 function 来过滤那些key属性与提供的值匹配的人。

While we could certainly find a way to make this point-free, I find this readable and understandable as it is, and probably wouldn't bother pursuing it.虽然我们当然可以找到一种方法来使这一点变得毫无意义,但我发现它是可读且易于理解的,并且可能不会费心去追求它。

You can use R.evolve to transform some of an object's properties without effecting the others:您可以使用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}
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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