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
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()
組合起來。
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
Conclusion
- 寫程式盡量避免
反向邏輯
,因為人類頭腦較能思考正向邏輯
- 當 predicate function 為
反向邏輯
時,建議使用reject()
取代filter()
Reference
以上所述就是小编给大家介绍的《Ramda 之 reject()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
嵌入式系统开发之道
2011-12 / 69.00元
《嵌入式系统开发之道:菜鸟成长日志与项目经理的私房菜》用平易朴实的语言,以一个完整的嵌入式系统的开发流程为架构,通过一位“菜鸟”工程师与项目经理的诙谐对话,故事性地带出嵌入式系统概念及开发要素,并点出要成为一名称职的嵌入式系统工程师,在实际工作中所必须具备的各项知识及技能。 《嵌入式系统开发之道:菜鸟成长日志与项目经理的私房菜》可以分为三大部分:第1、3、4、17、18、19章和附录D为嵌入......一起来看看 《嵌入式系统开发之道》 这本书的介绍吧!