[英]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。 只有當我提供第二個值(數組)時,我才能得到結果。
R.any
是Array#some
的 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.