Ramda 之 whereEq()
栏目: JavaScript · 发布时间: 6年前
内容简介:Ramda 的VS Code 1.31.1Quokka 1.0.136
Ramda 的 where() 可產生多個以 && 串起來的 Predicate,但若針對 Object,且都是 === 的 Predicate,就可以使用 whereEq() 更為精簡。
Version
VS Code 1.31.1
Quokka 1.0.136
Ramda 0.26.1
filter()
import { filter } from 'ramda';
const data = [
{ id: 1, title: 'Impatient JavaScript', year: 2018 },
{ id: 2, title: 'RxJS in Action', year: 2017 },
{ id: 3, title: 'Speaking JavaScript', year: 2014 }
];
const item = { title: 'RxJS in Action', year: 2017 };
const getBooks = filter(
x => x.title === item.title && x.year === item.year
);
const result = getBooks(data);
console.dir(result);
想要找出 title 等於 RxJS in Action 且 year 等於 2017 的 data ,且條件以 object 方式呈現。
11 行
const getBooks = filter( x => x.title === item.title && x.year === item.year );
使用了 Ramda 的 filter() 並搭配 predicate function,由於包含了兩個條件,因此必須使用 && 串起來。
whereEq()
import { filter, whereEq } from 'ramda';
const data = [
{ id: 1, title: 'Impatient JavaScript', year: 2018 },
{ id: 2, title: 'RxJS in Action', year: 2017 },
{ id: 3, title: 'Speaking JavaScript', year: 2014 }
];
const item = { title: 'RxJS in Action', year: 2017 };
const getBooks = filter(whereEq(item));
const result = getBooks(data);
console.dir(result);
filter() 的 predicate 可由 whereEq() 產生。
whereEq()
{String: *} → {String: *} → Boolean
比對兩個 object 的 property 是否相等
{String: *} :Spec object
{String: *} :Test object
Boolean :若相等傳回 true ,否則傳回 false
Spec object 的 property 可以少於 Test object
compose()
import { filter, whereEq, compose } from 'ramda';
const data = [
{ id: 1, title: 'Impatient JavaScript', year: 2018 },
{ id: 2, title: 'RxJS in Action', year: 2017 },
{ id: 3, title: 'Speaking JavaScript', year: 2014 }
];
const item = { title: 'RxJS in Action', year: 2017 };
const getBooks = compose(
filter,
whereEq(item)
)();
const result = getBooks(data);
console.dir(result);
原本 11 行
const getBooks = filter(whereEq(item));
先執行 whereEq() ,再將結果傳給 filter() 執行,因此也可以將 whereEq() 與 filter() 兩個 function 加以組合。
11 行
const getBooks = compose( filter, whereEq(item) )();
與一般 compose() 不同的是:最後還加上了 () ,因為 whereEq(item) 不需要任何參數,所以直接以 () 結束。
whereEq(item) 產生的 predicate 傳給 filter() 後,還留一個參數,這正是要傳給 getBooks() 的 data,因為 Point-free 而省略。
Conclusion
- 當 predicate 有多個條件,可使用
where() - 當 predicate 有多個條件,且資料來自於 object,並且只要判斷
===而已,則可使用whereEq() - 實務上不見的要使用
compose()重構,filter(whereEq(item))的寫法可讀性已經很高
Reference
以上所述就是小编给大家介绍的《Ramda 之 whereEq()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。