Ramda 之 find()

栏目: 编程语言 · 发布时间: 7年前

内容简介:Ramda 0.26.1簡單的需求,想找到

find() 為 Ramda 常用的 Operator,常搭配 propEq()equals() Operator 一併使用。

Version

Ramda 0.26.1

Imperative

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

const findBookById = (id, data) => {
  for(let item of data)
    if (item.id === id) return item;
};

const result = findBookById(1, books);
console.log(result);

簡單的需求,想找到 id1book object。

Imperative 會使用 for loop 搭配 if 判斷,若 id 找到就 return book object。

Ramda 之 find()

Array.prototype

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

const findBookById = (id, data) =>
  data.find(x => x.id === id);

const result = findBookById(1, books);
console.log(result);

Array.prototype 有內建 find() ,只要傳入 Arrow Function 即可。

Ramda 之 find()

Ramda

import { find, propEq } from 'ramda';

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

const finder = id => propEq('id', id);
const findBookById = (id, data) =>
  find(finder(id), data);

const result = findBookById(1, books); 
console.log(result);

Ramda 當然也有內建 find() ,其 signature 為

find()

(a → Boolean) → [a] → a | undefined

第一個參數為 a -> Boolean function,也就是 x => x.id === id

第二個參數為 [a] ,也就是 array。

若找到回傳為 a ,找不到回傳 undefined

第二個參數要自行傳入 Arrow Function 亦可,Ramda 特別提供 propEq() HOF 產生這類 Arrow Function。

propEq()

String -> a -> Object -> Boolean

第一個參數 String 為 object 的 property。

第二個參數 a 為要找的資料。

回傳為 Object -> Boolean ,也就是 find() 需要的 Arrow Function。

Ramda 之 find()

Q : propEq() 只適用於 array 內為 object,若為一般 value 呢 ?

import { find, equals } from 'ramda';

const data = [1, 2, 3];
const result = find(equals(1), data);
console.log(result);

Array 內若為一般 value,callback 就必須使用 equals()

equals()

a -> b -> Boolean

第一個參數 a 為要找的資料。

回傳 b -> Boolean ,也就是 find() 需要的 Arrow Function。

Ramda 之 find()

Conclusion

  • find() 為 Ramda 常用的 operator,其 callback 可搭配 propEq()equals() 產生

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

查看所有标签

猜你喜欢:

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

失控的真相

失控的真相

[美] 迈克尔·帕特里克·林奇 / 赵亚男 / 中信出版社 / 2017-6 / 42.00元

编辑推荐 在信息泛滥的时代,知识变得无处不在。鼠标轻轻一点,我们就坐拥一座巨型图书馆。然而,我们并没有因此就离真相更近。相反,互联网的普及使人们早已习惯于凡事问搜索引擎,并形成了一种“搜索即相信”的认知模式。当社交网络把数字人类带入一个个彼此隔绝的线上群体中,我们清楚地看到,真相与谎言在互联网中交织,知识与观念混为一谈,情绪宣泄掩盖了事实分析。联网的世界让我们更容易看到彼此的观点,但同时也制......一起来看看 《失控的真相》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试