Ramda reject - 有没有更优雅的方式来写这个?

Ramda reject - is there a more elegant way to write this?

const people = [
  {
    name: 'bill',
    age: 52
  },
  {
    name: 'james',
    age: 27
  },
  {
    name: 'james',
    age: 17
  }
]

const newPeople = R.reject(person => {
  return R.includes('jam', person.name)
})(people)

有没有更优雅的Ramda写法?我正在寻找 return 一个数组,该数组删除名称中包含字符串 jam 的所有人员对象。

也许是 R.reject(R.where(...)) 之类的东西?

谢谢!

我会把它分解成更小的功能:

withJam

Returns true 如果字符串包含字符串 jam(不区分大小写)

const withJam = R.test(/jam/i);
withJam('Bill') //=> false
withJam('James') //=> true

nameWithJam

Returns true 如果 属性 包含字符串 jam(不区分大小写)

const nameWithJam = R.propSatisfies(withJam, 'name');
nameWithJam({name: 'Bill'}) //=> false
nameWithJam({name: 'James'}) //=> true

那你可以这样写:

R.reject(nameWithJam)(people)

我认为您的初始解决方案已经足够好了。我只是让它成为 pointfree,即没有明确提及参数。

示例:

假设您需要一个将 5 添加到任意数字的函数:

const add5 = n => n + 5;
add5(37) //=> 42

如果您可以使用 add 的柯里化版本,您就可以摆脱 n。我们先定义add

const add = m => n => m + n;

然后让我们创建add5:

const add5 = add(5);
add5(37) //=> 42

你可以替换这个:

[1,2,3].map(n => n + 5) //=> [6,7,8]

有:

[1,2,3].map(add(5)) //=> [6,7,8]

⚠️ Pointfree 风格当然很有趣,值得探索。但它也会不必要地使事情复杂化 :) 请参阅

我认为您 where 的方向是正确的。

这对我来说非常好:

const jamless = reject (where ({name: includes ('jam')}))

const people = [{name: 'bill', age: 52}, {name: 'james', age: 27}, {name: 'james', age: 17}]

console .log (
  jamless (people)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script> const {reject, where, includes} = R                 </script>

大声朗读关键字,我们可以听到"reject where name includes 'jam'",不错的问题英文描述。

如果你想参数化这个,它可以是

const disallow = (str) => reject (where ({name: includes(str)}) )
const jamless = disallow ('jam')

(虽然我很确定我们可以制作 disallow 的无积分版本,但我认为没有理由尝试,因为这已经非常可读了。)

另见相关回答,