【问题标题】:Reverse boolean return of function in RamdaRamda中函数的反向布尔返回
【发布时间】:2020-02-26 21:23:55
【问题描述】:

我刚刚开始探索 Ramda 库并遇到了一些问题。

假设我们有一个函数,它将字符串和字符串列表作为参数,如果给定的字符串在列表中,则返回 true。在第 4 行,我想记录otherList包含在list 中的第一个元素。

const isInList = R.curry((name: string, list: string[]) => list.some(elem => elem === name))
const list = ['a', 'b', 'c']
const otherList = ['a', 'b', 'd', 'c']
console.log(otherList.find(!isInList(R.__, list)))

我找不到可以反转给定函数的逻辑结果的 Ramda 函数。

如果它存在,它看起来像这样:

const not = (func: (...args: any) => boolean) => (...args: any) => !func(args)

然后我的目标可以归档为:

console.log(otherList.find(not(isInList(R.__, list)))

Ramda 有这样的功能吗?

【问题讨论】:

  • 是的,你发现它是R.complement。函数R.not 用于更简单的事情:采用逻辑not 的布尔值(或者实际上是任何false-y/truth-y JS 值。)

标签: javascript typescript functional-programming ramda.js


【解决方案1】:

R.complement 是对函数求反的方式

const isInList = R.includes;
const isNotInList = R.complement(isInList);

const list = ['Giuseppe', 'Francesco', 'Mario'];

console.log('does Giuseppe Exist?', isInList('Giuseppe', list));
console.log('does Giuseppe Not Exist?', isNotInList('Giuseppe', list));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js" integrity="sha256-xB25ljGZ7K2VXnq087unEnoVhvTosWWtqXB4tAtZmHU=" crossorigin="anonymous"></script>

【讨论】:

    【解决方案2】:

    试试 R.difference():

    const list = ['a', 'b', 'c']
    const otherList = ['a', 'b', 'd', 'c']
    R.difference(otherList, list); //=> ['d']
    

    在线演示here

    【讨论】:

    • 也许它与我的问题无关,但它非常有用,谢谢!
    【解决方案3】:

    找到了!它叫R.complement()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 2021-09-27
      • 2012-07-15
      • 2013-03-11
      相关资源
      最近更新 更多