Ramda 之 reject()

栏目: JavaScript · 发布时间: 5年前

内容简介:VS Code 1.31.1Quokka 1.0.136

filter() 是 FP 代表性的 operator,但若想表達的是 請將符合條件的資料不顯示 ,當然也可以繼續使用 filter() 搭配 反向邏輯 ,語義則變成 請將不符合條件資料顯示 ;Ramda 特別提供了 reject() ,讓我們能夠使用 正向邏輯 表示。

Version

VS Code 1.31.1

Quokka 1.0.136

Ramda 0.26.1

filter()

import { filter } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = filter(x => x.title !== 'RxJS in Action');
console.dir(getBooks(data));

若我們想找出所有 title 不是 RxJS in Action 的書,若使用 filter() ,勢必使用 反向邏輯 ,也就是 !==

filter()

(a -> Boolean) -> [a] -> [a]

回傳符合條件的 array

Ramda 之 reject()

Point-free

import { filter, propEq, compose, not } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = filter(compose(
  not,
  propEq('title', 'RxJS in Action')
));
console.dir(getBooks(data));

若要求 predicate function 為 Point-free,則必須使用 compose()propEq()not() 組合起來。

Ramda 之 reject()

reject()

import { reject, propEq } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = reject(propEq('title', 'RxJS in Action'));
console.dir(getBooks(data));

reject()filter() 的 complement function,因此 predicate 直接提供 正向邏輯 即可。

reject()

(a → Boolean) → [a] → [a]

將符合條件的資料去除,並回傳新的 array

(a -> Boolean) :Predicate function,指定去除的條件

[a] :data 為 array

[a] :回傳去除資料後的新 array

Ramda 之 reject()

Conclusion

  • 寫程式盡量避免 反向邏輯 ,因為人類頭腦較能思考 正向邏輯
  • 當 predicate function 為 反向邏輯 時,建議使用 reject() 取代 filter()

Reference

Ramda , filter()

Ramda , reject()


以上所述就是小编给大家介绍的《Ramda 之 reject()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

嵌入式系统开发之道

嵌入式系统开发之道

2011-12 / 69.00元

《嵌入式系统开发之道:菜鸟成长日志与项目经理的私房菜》用平易朴实的语言,以一个完整的嵌入式系统的开发流程为架构,通过一位“菜鸟”工程师与项目经理的诙谐对话,故事性地带出嵌入式系统概念及开发要素,并点出要成为一名称职的嵌入式系统工程师,在实际工作中所必须具备的各项知识及技能。 《嵌入式系统开发之道:菜鸟成长日志与项目经理的私房菜》可以分为三大部分:第1、3、4、17、18、19章和附录D为嵌入......一起来看看 《嵌入式系统开发之道》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码