Ramda 之 reject()
栏目: JavaScript · 发布时间: 6年前
内容简介: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()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C#图解教程
索利斯 (Daniel M.Solis) / 姚琪琳、苏林、朱晔 / 人民邮电出版社 / 2013-7-1 / CNY 89.00
本书是广受赞誉的C# 图解教程的最新版本。作者在本书中创造了一种全新的可视化叙述方式,以图文并茂的形式、朴实简洁的文字,并辅以大量表格和代码示例,全面、直观地阐述了C# 语言的各种特性。新版本除了精心修订旧版内容外,还全面涵盖了C# 5.0 的新增特性,比如异步编程、调用者信息、case 表达式、带参数的泛型构造函数、支持null 类型运算等。通过本书,读者能够快速、深入理解C#,为自己的编程生涯......一起来看看 《C#图解教程》 这本书的介绍吧!