无法捕获 "R.applySpec" 中的参数:Ramda.js

Unable to catch arguments in "R.applySpec" : Ramda.js

我基本上是想在 R.applySpec.

中实现下面的代码
const fn = ({target, count}) => R.unnest (R.zipWith (R.repeat) (target, count))

const Data = { 
  target : ["a", "b", "c"], 
  count : [1, 2, 3],
}

const data1= {
  result : fn (Data)
}
console.log ( 'data1:', data1.result);// ["a","b","b","c","c","c"]

我想不通的是 fn 中的参数似乎在 R.applySpec

中未被捕获
const data2_applySpec = R.applySpec({
  result : R.lift ( R.zipWith ( fn )) ( R.prop ('target'),  R.prop ('count'))
})

const data2 = data2_applySpec(Data)
console.log ('data2:', data2);//ERROR

如何修改 fn 使其正常工作? 我使用 Ramda.js。 谢谢。

REPL

您可以使用 R.props 的数组数组 ([target, count]),将数组的数组应用于 R.zipWith(repeat),然后使用 R.unnest 展平结果:

const { applySpec, pipe, props, apply, zipWith, repeat, unnest } = R

const Data = { 
  target : ["a", "b", "c"], 
  count : [1, 2, 3],
}

const data2_applySpec = applySpec({
  result: pipe(props(['target', 'count']), apply(zipWith(repeat)), unnest)
})

const result = data2_applySpec(Data)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>

我认为你让这件事变得比需要的更难了。

您已经将要在 applySpec 中使用的函数存储为 fn

所以你可以写:

const fn2 = applySpec ({
  result: fn
})

或者,如果您对 fn 的唯一使用是在此 applySpec 调用中,则只需将其内联:

const fn3 = applySpec ({
  result: ({target, count}) => unnest (zipWith (repeat) (target, count))
})

如果您对 point-free 代码情有独钟,您可以使用 :

中讨论的技术
const fn4 = applySpec ({
  result: compose (unnest, apply (zipWith (repeat)), props (['target', 'count']))
})

(或 Ori Drori 的类似版本。)

所有这些都显示在此代码段中。

const fn1 = ({target, count}) => unnest (zipWith (repeat) (target, count))

const fn2 = applySpec ({
  result: fn1
})

const fn3 = applySpec ({
  result: ({target, count}) => unnest (zipWith (repeat) (target, count))
})

const fn4 = applySpec ({
  result: compose (unnest, apply (zipWith (repeat)), props (['target', 'count']))
})


const data = {target : ["a", "b", "c"], count : [1, 2, 3]}

console .log (fn1 (data))
console .log (fn2 (data))
console .log (fn3 (data))
console .log (fn4 (data))
.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 {unnest, zipWith, repeat, applySpec, compose, apply, props} = R </script>