我正在尝试用js做一个类似.some的东西,但是用的是ramda.js。我不明白是怎么回事。我有一个对象数组,如果一些对象具有array.length > 1的value属性,我希望得到true/false。
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)但我想和拉姆达一起做。试着这样做,但它不起作用:
const isHasSomeValues = R.gt(R.length(R.prop('value')), 1);
console.log(R.any(isHasSomeValues)(features))发布于 2021-04-28 21:39:23
R.any是一个谓词函数,而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>
要创建一个由多个函数组合而成的函数,可以使用R.pipe或R.compose执行一组操作,其中每个操作都接收前一个操作的结果。管道中的第一个操作(函数)是使用传递到管道的值调用的-在本例中是一个对象。
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中还有其他组合函数的方法,其中之一就是currying。Ramda的所有函数都是curried的,并且它们都有一个固定的数量(函数接受的参数数量)。这意味着,如果将单个参数传递给需要2的函数,您将返回一个部分应用的函数。只有当你提供第二个参数时,函数才会返回结果。
在本例中,R.any的参数为2。我将谓词(pipe(...))传递给它,并获得一个新函数。只有当我提供第二个值(数组)时,我才会得到结果。
发布于 2021-04-28 23:40:59
的Ramda等价物
我可能会这样做:属性值不为空吗?,因为你对值包含多少项并不真正感兴趣……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>
https://stackoverflow.com/questions/67301146
复制相似问题