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

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()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Spark大数据分析技术与实战

Spark大数据分析技术与实战

董轶群、曹正凤、赵仁乾、王安 / 电子工业出版社 / 2017-7 / 59.00

Spark作为下一代大数据处理引擎,经过短短几年的飞跃式发展,正在以燎原之势席卷业界,现已成为大数据产业中的一股中坚力量。 《Spark大数据分析技术与实战》着重讲解了Spark内核、Spark GraphX、Spark SQL、Spark Streaming和Spark MLlib的核心概念与理论框架,并提供了相应的示例与解析。 《Spark大数据分析技术与实战》共分为8章,其中前4......一起来看看 《Spark大数据分析技术与实战》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具