对于数组中的重复值,如何使用 "repeat" 和 Ramda.js

For duplicate values in an array, how do I use "repeat" with Ramda.js

我正在尝试用 count:[1, 2, 3]

复制 target:[ "a", "b", "c"]

理想的输出是["a", "b", "b", "c", "c", "c"]

它不适用于此代码:

const fn = ({ target, count }) => R.map (R.repeat (target, count))

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

const result = fn(Data)

我正在尝试使用 Ramda.js 找到解决方案。

谢谢。

大概是这样的:

const fn = R.pipe(
  R.props(['target', 'count']),
  R.apply(R.zip),
  R.chain(R.apply(R.repeat)),
);
  

// ===

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

console.log(
  fn(data),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>

另一个相当简单的解决方案:

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

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

console .log (fn (data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {unnest, zipWith, repeat} = R                             </script>

targetdata 的 point-free 函数很简单:

compose (unnest, zipWith (repeat))

如果它们被包裹在一个对象中并且你真的想要 point-free,那么 Hitmands 的答案似乎是最好的,或者使用这种技术的变体:

compose (unnest, apply (zipWith (repeat)), props (['target', 'count']))