Ramda 之 useWith()
栏目: JavaScript · 发布时间: 6年前
内容简介:對於只有一個參數的 function,我們可以很輕易地 Point-free,對於兩個以上參數的 function 呢 ? 這時就要使用 Ramda 殺手級 operator:WebStorm 2018.3.3Quokka 1.0.136
對於只有一個參數的 function,我們可以很輕易地 Point-free,對於兩個以上參數的 function 呢 ? 這時就要使用 Ramda 殺手級 operator: useWith() 。
Version
WebStorm 2018.3.3
Quokka 1.0.136
Ramda 0.26.1
Non Point-free
import { find, propEq } from 'ramda';
const data = [
{ id: 1, title: 'Functional Programming in JavaScript' },
{ id: 2, title: 'RxJS in Action' },
{ id: 3, title: 'Speaking JavaScript' },
];
const getBook = (id, data) => find(propEq('id', id), data);
console.dir(getBook(1, data));
若我們想根據 id 找資料,建立了 getBook() ,其中第一個參數為要搜尋的 id ,第二個參數為 data ,再使用 find() 找到該 object。
find()
(a -> boolean) -> [a] -> a | undefined
根據 predicate function 搜尋 array 中的資料
這樣寫是 OK 的,唯 getBook() 尚有兩個參數 id 與 data ,並不是 Point-free。
Point-free
import { find, propEq, useWith, identity } from 'ramda';
const data = [
{ id: 1, title: 'Functional Programming in JavaScript' },
{ id: 2, title: 'RxJS in Action' },
{ id: 3, title: 'Speaking JavaScript' },
];
/** a -> [a] -> a | undefined */
const getBook = useWith(find, [propEq('id'), identity]);
console.dir(getBook(1, data));
對於這種超過一個參數的 function,若我們想做 Point-free,我們可以使用 Ramda 的 useWith() ,他將回傳一個新的 curried function,且參數個數與原本 function 相同,最重要它是 Point-free。
useWith()
((x1, x2, ...) -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z)
建立一個與原 function 參數個數相同的新 function,且各參數會先經過 transform function 處理過再傳給原 function 執行
((x1, x2, ...) -> z) :原本尚未 curried、尚未 Point-free 的 function
[(a -> x1), (b -> x2), ...] :為 array,有幾個參數就會有幾個 transformer function,新 function 的所有參數,都會經過 transformer function 執行過,結果才會傳給原 function
(a -> b -> ... -> z) :回傳新 function,且是 curried function
第 9 行
const getBook = (id, data) => find(propEq('id', id), data);
/** a -> [a] -> a | undefined */
const getBook = useWith(find, [propEq('id'), identity]);
要將 getBook() 重構成 Point-free 很簡單:
- 將
find放在useWith()的第一個參數 - 將原本 在
find()第二個參數的propEq('id')改寫在 array 內 -
id不變,則使用identity()
identity()
a -> a
建立傳回原本值的 function
如此 id 與 data 兩參數就被幹掉了,成了 Point-free。
useWith() 寫法雖然精簡,但 Point-free 版本日後可能一時看不出其 signature,建議馬上補上 signature 註解,其格式可模仿 Ramda 官網文件
Conclusion
useWith() useWith()
Reference
以上所述就是小编给大家介绍的《Ramda 之 useWith()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
程序员代码面试指南:IT名企算法与数据结构题目最优解(第2版)
左程云 / 电子工业出版社 / 109.00元
《程序员代码面试指南:IT名企算法与数据结构题目最优解(第2版)》是一本程序员代码面试"神书”!书中对IT名企代码面试各类题目的最优解进行了总结,并提供了相关代码实现。针对当前程序员面试缺乏权威题目汇总这一痛点,本书选取将近300道真实出现过的经典代码面试题,帮助广大程序员的面试准备做到接近万无一失。"刷”完本书后,你就是"题王”!《程序员代码面试指南:IT名企算法与数据结构题目最优解(第2版)》......一起来看看 《程序员代码面试指南:IT名企算法与数据结构题目最优解(第2版)》 这本书的介绍吧!