繁体   English   中英

Ramda.js 中的一些内容

[英]Some in Ramda.js

我正在尝试在 js 中做类似的事情,但使用 ramda.js。 我不明白怎么做。 我有一个对象数组,如果某些 object 的 value 属性具有 array.length > 1,我想得到一个真/假。

const features = [
{
    name: "First name",
    type: "First type",
    value: ["First value 1", "First value 2"],
},
{
    name: "Second name",
    type: "Second type",
    value: ["Second value 1"],
}
];

在 vanilla.js 中,它可以是:

features.some((f) => f.value.length > 1)

但我想用 Ramda 来做。 试试这个,但它不起作用:

const isHasSomeValues = R.gt(R.length(R.prop('value')), 1);
console.log(R.any(isHasSomeValues)(features))

R.any 除了一个谓词 function, isHasSomeValues实际上是一个false值:

 const isHasSomeValues = R.gt(R.length(R.prop('value')), 1); console.log(isHasSomeValues);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>

To create a function that is a combination of multiple functions you can use R.pipe or R.compose to perform a set of actions, where each action receives the result of the previous one. 使用传递给 pipe 的值调用管道中的第一个操作(函数) - 在您的情况下为 object。

 const { pipe, any, prop, length, gt, __ } = R const fn = any(pipe( prop('value'), // get the value array length, // get the length gt(__, 0), // check if the length is greater than 0 )) const features = [{"name":"First name","type":"First type","value":["First value 1","First value 2"]},{"name":"Second name","type":"Second type","value":["Second value 1"]}] const result = fn(features) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.js" integrity="sha512-3sdB9mAxNh2MIo6YkY05uY1qjkywAlDfCf5u1cSotv6k9CZUSyHVf4BJSpTYgla+YHLaHG8LUpqV7MHctlYzlw==" crossorigin="anonymous"></script>

在 Ramda 中还有其他组合函数的方法,其中之一是柯里化。 Ramda 的所有函数都是curried ,并且它们都具有固定的数量(function 接受的参数数量)。 这意味着如果将单个参数传递给需要 2 的 function,您将返回部分应用的 function。 只有当您提供第二个参数时,function 才会返回结果。

在这种情况下,R.any 的元数为 2。我将谓词( pipe(...) )传递给它,并得到一个新的 function。 只有当我提供第二个值(数组)时,我才能得到结果。

我可能会像道具值不为空一样接近这个? ,因为您对值包含多少项并不真正感兴趣... gt 0就足够了。

 const isValueEmpty = R.propSatisfies(R.isEmpty, 'value'); const fn = R.any( R.complement(isValueEmpty), ); const data = [ { name: 'First name', type: 'First type', value: ['First value 1', 'First value 2'], }, { name: 'Second name', type: 'Second type', value: ['Second value 1'], }, ]; 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>

暂无
暂无

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

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